2013. 11. 19. 09:56
date -s YYYYMMDD.HHmmss

adb shell setprop persist.sys.timezone "America/Chicago"
from datetime import datetime

date_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

Link to the Python documentation for strptime

and a link for the strftime format mask

8.1.7. strftime() and strptime() Behavior

datedatetime, and time objects all support a strftime(format) method, to create a string representing the time under the control of an explicit format string. Broadly speaking, d.strftime(fmt) acts like the time module’s time.strftime(fmt, d.timetuple()) although not all objects support a timetuple() method.

Conversely, the datetime.strptime() class method creates a datetime object from a string representing a date and time and a corresponding format string. datetime.strptime(date_string, format) is equivalent to datetime(*(time.strptime(date_string, format)[0:6])).

For time objects, the format codes for year, month, and day should not be used, as time objects have no such values. If they’re used anyway, 1900 is substituted for the year, and 1 for the month and day.

For date objects, the format codes for hours, minutes, seconds, and microseconds should not be used, as date objects have no such values. If they’re used anyway, 0 is substituted for them.

The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common. To see the full set of format codes supported on your platform, consult the strftime(3)documentation.

The following is a list of all the format codes that the C standard (1989 version) requires, and these work on all platforms with a standard C implementation. Note that the 1999 version of the C standard added additional format codes.

The exact range of years for which strftime() works also varies across platforms. Regardless of platform, years before 1900 cannot be used.

DirectiveMeaningExampleNotes
%aWeekday as locale’s abbreviated name.
Sun, Mon, ..., Sat (en_US);
So, Mo, ..., Sa (de_DE)
(1)
%AWeekday as locale’s full name.
Sunday, Monday, ..., Saturday (en_US);
Sonntag, Montag, ..., Samstag (de_DE)
(1)
%wWeekday as a decimal number, where 0 is Sunday and 6 is Saturday.0, 1, ..., 6 
%dDay of the month as a zero-padded decimal number.01, 02, ..., 31 
%bMonth as locale’s abbreviated name.
Jan, Feb, ..., Dec (en_US);
Jan, Feb, ..., Dez (de_DE)
(1)
%BMonth as locale’s full name.
January, February, ..., December (en_US);
Januar, Februar, ..., Dezember (de_DE)
(1)
%mMonth as a zero-padded decimal number.01, 02, ..., 12 
%yYear without century as a zero-padded decimal number.00, 01, ..., 99 
%YYear with century as a decimal number.1970, 1988, 2001, 2013 
%HHour (24-hour clock) as a zero-padded decimal number.00, 01, ..., 23 
%IHour (12-hour clock) as a zero-padded decimal number.01, 02, ..., 12 
%pLocale’s equivalent of either AM or PM.
AM, PM (en_US);
am, pm (de_DE)
(1), (2)
%MMinute as a zero-padded decimal number.00, 01, ..., 59 
%SSecond as a zero-padded decimal number.00, 01, ..., 59(3)
%fMicrosecond as a decimal number, zero-padded on the left.000000, 000001, ..., 999999(4)
%zUTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).(empty), +0000, -0400, +1030(5)
%ZTime zone name (empty string if the object is naive).(empty), UTC, EST, CST 
%jDay of the year as a zero-padded decimal number.001, 002, ..., 366 
%UWeek number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0.00, 01, ..., 53(6)
%WWeek number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.00, 01, ..., 53(6)
%cLocale’s appropriate date and time representation.
Tue Aug 16 21:30:00 1988 (en_US);
Di 16 Aug 21:30:00 1988 (de_DE)
(1)
%xLocale’s appropriate date representation.
08/16/88 (None);
08/16/1988 (en_US);
16.08.1988 (de_DE)
(1)
%XLocale’s appropriate time representation.
21:30:00 (en_US);
21:30:00 (de_DE)
(1)
%%A literal '%' character.% 

Notes:

  1. Because the format depends on the current locale, care should be taken when making assumptions about the output value. Field orderings will vary (for example, “month/day/year” versus “day/month/year”), and the output may contain Unicode characters encoded using the locale’s default encoding (for example, if the current locale is ja_JP, the default encoding could be any one of eucJPSJIS, or utf-8; use locale.getlocale() to determine the current locale’s encoding).

  2. When used with the strptime() method, the %p directive only affects the output hour field if the %I directive is used to parse the hour.

  3. Unlike the time module, the datetime module does not support leap seconds.

  4. %f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available). When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right.

    New in version 2.6.

  5. For a naive object, the %z and %Z format codes are replaced by empty strings.

    For an aware object:

    %z

    utcoffset() is transformed into a 5-character string of the form +HHMM or -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and MM is a 2-digit string giving the number of UTC offset minutes. For example, ifutcoffset() returns timedelta(hours=-3, minutes=-30)%z is replaced with the string '-0330'.

    %Z

    If tzname() returns None%Z is replaced by an empty string. Otherwise %Z is replaced by the returned value, which must be a string.

  6. When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the year are specified.

Footnotes

[1]

If, that is, we ignore the effects of Relativity

View Full Version : HOW-TO: Set system time clock with rdate


Mr. Gadget
02-08-2011, 08:29 PM
Set your system time with RDATE or NTPD

You can set your PBO system time clock to the current time using the command 'rdate'. You will need to download and add the latest Busybox commands (do not overlay on existing commands, unless you know what you are doing). 

1) Perform the addition of the latest Busybox commands to your system. You can run them from your HD or USB, not sure about using internal memory. The Busybox file is only 1.6Mb, but I would not want to deny the OS from using available space. If you want to test this feature before making it permanent, insert a USB drive on the PBO, browse to the USB drive from your PC, map it to a drive letter like V:, then download busybox-mipsel.asc file to the mapped/USB drive (save target, and add the file extension .asc).

Snappy has this file information listed here: http://www.patriotmem.com/forums/showthread.php?t=3737

A quick test to see if the new BBox commands work (I placed my file in the root of the front USB, which is /tmp/usbmounts/sda1). 

Create an alias to your new commands on Venus:

Venus> alias bb="/tmp/usbmounts/sda1/busybox-mipsel.asc"

Test it with 'whoami', it should return root, if you get "-sh: whoami: not found" you are not linked to the proper file.

Venus> bb whoami
root


2) Next you should modify your /etc/profile to match your proper TZ (timezone). Example: TZ=MST7MDT
This will allow you to see your time in your local format (assuming the timezone file is current for your location, too detailed for this mod).

You can display the 'current' set date/time for your timezone, but if you did not set the date manually already, it will be wrong. Just enter the command 'date'. Don't worry about any of the fields other than your timezone, ie MST, PST...

3) Now your system is armed to get access and display the proper time. So, first we will update the System clock from the network. We need to use an older time server since most do not accept the rdate protocol command. If we can get NTP loaded on the PBO, then we can use any Stratum NTP server available (pool.ntp.org). 

Enter the command:

Venus> bb rdate -sp time-nw.nist.gov
Tue Feb 8 12:53:33 2011

So now your system has the correct time. But the hardware clock is still out of sync with the system time. We can view this using the 'hwclock' command.

Venus> hwclock
Thu Dec 31 17:12:33 2009 0000000000.000000 seconds

Let's fix the hardware clock and sync it with the system clock.

Venus> hwclock -w

Now verify the System clock and Hardware clock are in sync. Just enter the 'date' command, then compare with the 'hwclock' command results.

Your system is now set to the current time, and your display should be set to your local timezone.

Update: Use NTP to set clock. Can ignore hwclock settings at this point in time, the RTC does not advance after setting anyway.

(Verbose mode)
Venus> bb ntpd -dnq -p pool.ntp.org

(Quiet mode)
Venus> bb ntpd -nq -p pool.ntp.org


TODO:
Decide which clock is more important: System (telnet) time, or PBO (GUI) time.
(GUI Time displays UTC time, telnet system clock shows TZ time).

Make it permanent (every system boot).

DONE:
Install NTP for greater accuracy and more system support. Part of the new busybox command set.

WOW -- The hwclock clock NEVER advances automatically - something I hadn't noticed at first. I thought it was slow.
aasoror
02-08-2011, 11:35 PM
Excellent write up,
Thanks,
IanC
02-09-2011, 06:48 AM
I suspect the "drift" is why some of the firmwares have dropped the ability to set the time.
grill
03-20-2011, 06:04 PM
The NTPD work fine, but how did that NTPD refresh automatically every time when I turn on the PBO? :rolleyes:
aasoror
03-20-2011, 09:09 PM
The NTPD work fine, but how did that NTPD refresh automatically every time when I turn on the PBO? :rolleyes:

You can add whatever commands that starts the service to your /usr/local/etc/rcS (startup script).
grill
03-21-2011, 07:01 PM
Thank you! :)
jamaroney
05-21-2012, 11:31 AM
I installed busybox 1.18.1 on my PBO successfully. When I run "ntpd -nq -p pool.ntp.org" via telnet after startup, it works fine, but it doesn't work when I put it in rcS. Am I doing anything wrong, or will it simply not work in the startup script?
snappy46
05-21-2012, 03:11 PM
I installed busybox 1.18.1 on my PBO successfully. When I run "ntpd -nq -p pool.ntp.org" via telnet after startup, it works fine, but it doesn't work when I put it in rcS. Am I doing anything wrong, or will it simply not work in the startup script?

My guess would be that your network connection is not active yet when running from the rcS file. I personnally only have one extra entry in my rcS file to another script which make all the magic happen. The first thing that happen in my script is a loop to make sure my network (wireless/ethernet) is up an running before anything happen. After that loop is completed I then mount my NAS, setup the time, launch lighttpd etc......

Hope this helps!

Cheers!!!
Mr. Gadget
05-21-2012, 05:54 PM
I have a few dirty programs I use to boot my system. 
First, I added a call in the rcS1 file to myStartup.sh (see imbedded comment)

Then, myStartup.sh calls all of my utilities to do my system setup:
1) Run setMGWY.sh to determine what the default gateway should be
2) Run chknet.sh to see if the network is operational yet
3) Run getTime.sh to set the time using NTPD
4) Run myMount.sh to mount my SMB shares (not included here)

You may name the programs with our without the .sh, if you add, then be sure to edit the files to include the correct name. 
(By default, the only file with .sh is myStartup.sh)

File: myStartup.sh


File: myStartup.sh

#!/bin/sh
# myStartup.sh
# Date: 20110804 V1.21
# Date: 20120103 V1.21b Change from HDD to USB (Mars), Removed SYSLOG and looger (too much memory used)
# Date: 20120521 V1.21c Cleanup
# This program will check the status of the network, if up 
# it will set time, mount shares, and whatever else is needed if network up.
# If network down, you can do something else.
# If used in rcS1, be sure to make verbose 0 (no output)
# Expects busybox to be in ???

# Add/Edit your /etc/init.d/rcS1 - (remove comments ##!# below) 120103 (mount -o remount,rw /)
### file rcS1
### Added 120103 - If usb attached. wait till ready, run myStartup commands, else bypass
##!#sleep 20
##!#if [ -e /tmp/usbmounts/sdb1/bin/scripts/myStartup.sh ]; then
### echo "File exists"
##!# /tmp/usbmounts/sdb1/bin/scripts/myStartup.sh&
##!#fi

# Usually, the IP is for the router/gateway
# Programs used: 
# Syntax: 
# chknet [-i IP|MGWY] [-c count] [-q] [-h]
# getTime [-q]
# setMGWY [-q]
# myMount [-q]
# Start USER DEFINED Programs:
CKNET="/tmp/usbmounts/sdb1/bin/scripts/chknet"
STMGY="/tmp/usbmounts/sdb1/bin/scripts/setMGWY"
GTIM="/tmp/usbmounts/sdb1/bin/scripts/getTime"
MYMNT="/tmp/usbmounts/sdb1/bin/scripts/myMount"
# End USER DEFINED Programs

# Start SYSLOG (too much memory used)
##/etc/init.d/syslog.rcS -p /tmp/hdd/volumes/HDD1/logs/syslog&
#logger " $(date) - Syslog started at boot"

# Locate the Default gateway router, set MGWY variable (this may have trouble - redo to file?)
. $STMGY

# TEMP What is set?
##set

# See if network is operational
$CKNET -q
# Save the exit status of last command
status=$?
if [ $status == 0 ];
then
# Do something if network is UP
##echo "GOOD Status is (0 or 0)" $? " chknet status is " $status
# Set the Time of day from NTP
$GTIM -q
# Mount my SMB shares
$MYMNT -q
#logger " $(date) - MyStartup completed succesfully"
else
# Do something if network is DOWN
##echo "BAD Status is (1 or 100)" $? " chknet status is " $status
logger " $(date) - MyStartup did not complete succesfully, Status: $status"
fi 
# and finis

# end myStartup


Next post included files (too long for original post)

Good Luck, hope these help.
Mr. Gadget
05-21-2012, 05:56 PM
Part 2, Utility Files

File: setMGWY


File: setMGWY.sh

#!/bin/sh
# Date: 20110628 v1.1
tver="v1.1"
# By: Mr. Gadget
# Script: setMGWY
# Purpose: Create a Global variable MGWY used other programs, such as:
# chknet, getTime, myMount ...
# Use netstat to locate Gateway, save to temp file, and make global variable MGWY.
# (Others may find faster methods to accomplish same).
# Note: To make variable global (parent shell) use ". path/setMGWY"
#
# Input: None
# Output: Environment variable MGWY
#####################################
# Identify our current gateway. Not sure what it looks like if no network.
netstat -r -n | grep ^0.0.0.0 | awk '{print $2}' >/tmp/mynet.tmp
read MGWY </tmp/mynet.tmp
# Debug echo (uncomment #.#)
#.#echo "MGWY is $MGWY"
export MGWY
# Debug export (uncomment #.#)
#.#export
# end setMGWY


File: chknet


File: chknet.sh

#!/bin/sh
# Date: 20110628 v5.4
# Date: 20110928 v5.4a Modify from HDD to USB - Use Direct link to awk (gawk)
# Date: 20120112 v5.4b awk fixed with MegaPack Update
tver="v5.4b"
# By: Mr. Gadget
# Script: chknet [-i IP] [-c count] [-q] [-h]
# where -i IP = xxx.xxx.xxx.xxx (or $MGWY)
# -c count = 1-n (1=22seconds, 2=33seconds, 3=44...) delay (or $PLOOP)
# -q (quiet, otherwise verbose) (or $VERBOSE=0 or 1)
# Status Returns: 0 if network up, 1 invalid input, 2 invalid BusyBox, 100 if network down
# Purpose:
# This script will loop on checking the network status Up or Down, 
# and then return status code 0 for UP and 100 for DOWN.
# The loop count is user selectable to avoid endless loop.
# DO NOT RUN IN VERBOSE MODE within your rcS
# This program REQUIRES the updated BusyBox (V1.16+) command parser
# with the extra PING features. 
# Get the advanced Busybox here (save with extension .asc)
# http://busybox.net/downloads/binaries/1.16.1/busybox-mipsel
# also
# http://playon.unixstorm.org/download/tools/busybox1.18.3
# Tip: Make an alias in /etc/profile, 
# alias bb="/tmp/hdd/volumes/HDD1/bin/busyboxxxxx.asc"
# for ongoing use of the advanced busybox commands for interactive use.

##### USER-SPECIFICS
# Choices for file locations of your Busybox binaries:
# Internal HDD Small partition /tmp/hdd/root (part3 = 512MB, type ext3)
# Internal HDD Large partition /tmp/hdd/volumes/HDD1 (part1 = 500GB, type ufsd)
# Removable USB /tmp/usbmounts/sdb1 (host3 part1 = 8GB, type vfat)
# Removable USB /tmp/usbmounts/sda1 (UNUSED)
# Define where your updated BusyBox image is located (not Flash)
# I use the bin folder on the USB drive for this PBO (in case I need to remove it to bypass my startups)
#MBB="/tmp/hdd/volumes/HDD1/bin/busybox-mipsel.asc"
#MBB="/tmp/hdd/volumes/HDD1/bin/busybox1.18.3.asc"
MBB="/tmp/usbmounts/sdb1/bin/busybox1.18.3.asc"
# Bug in previous BB. If needed, Use awk file /usr/local/bin/package/awk" (FIXED with MegaPack update)


### Define your default gateway if you want
tmgwy="192.168.1.253"
### Define Default loop count 1=22sec, 2=33sec, 3=44sec ...
tploop=5
### Define Default Verbose (not quiet).
tverbose=1
#### END USER-SPECIFICS

### oh, check to see if we have access to a good BusyBox image, exit error 2 if not found
if [ ! -s "$MBB" ]; 
then
echo "No path to extended Busybox file"
exit 2
fi

### OK to proceed if updated Busybox available

### Test if input options specified, or use Global vars ($MGWY, $PLOOP, $VERBOSE)
args=`getopt i:c:qh $*`
if test $? != 0
then
echo 'Version: '$tver;\
echo 'Usage: '$0' [OPTIONS]'; echo '';\
echo 'Options:'; echo ' -i IP Check if Host IP is Up/Down'; \
echo ' Global Variable $MGWY may be used.'; \
echo ' -c CNT Loop delay count, [5] = 66 seconds'; \
echo ' Global Variable $PLOOP may be used.'; \
echo ' -q Quiet mode. No output.'; \
echo 'Status:'; echo ' 0 = Host up, 1 = invalid input, 2 = invalid Busybox file, 100 = Host down' 
exit 1
fi

### We may or may not have input, set the arguments
#.#echo "Args are: " $args
set -- $args

### Parse out the arguments, and shift as required.
for i
do
case "$i" in
-i) opt_i=$2;shift;shift;;
-c) opt_c=$2;shift;shift;;
-q) opt_q=$1;shift;;
-h) echo ''; \
echo 'chknet Version: '$tver;\
echo 'Usage: '$0' [OPTIONS]'; echo '';\
echo 'Options:'; echo ' -i IP Check if Host IP is Up/Down'; \
echo ' Global Variable $MGWY may be used.'; \
echo ' -c CNT Loop delay count, [5] = 66 seconds'; \
echo ' Global Variable $PLOOP may be used.'; \
echo ' -q Quiet mode. No output.'; \
echo 'Status:'; echo ' 0 = Host up, 1 = invalid input, 2 = invalid Busybox file, 100 = Host down'
exit 1
esac
done

### If we did not pass any (-i) IP options, use either the global exported MGWY or assign a gateway.
if [ -n "$opt_i" ];
then
### Do something if TRUE, like save the -i input
###echo "Valid var opt_i=$opt_i, use it"
MGWY=$opt_i
else
### Do something if FALSE, like assign the Global var or a temp IP
###echo "Try if global MGWY=$MGWY, else set to temp gateway"
[ "$MGWY" ] || MGWY="$tmgwy"
fi

### If we did not pass any (-c) COUNT options, use either the global exported PLOOP or assign a value
if [ -n "$opt_c" ];
then
### Do something if TRUE, like save the -c input
###echo "Valid var opt_c=$opt_c, use it"
PLOOP=$opt_c
else
### Do something if FALSE, like assign the Global var or a temp CNT
###echo "Try if global PLOOP=$PLOOP, else set to temp count"
[ "$PLOOP" ] || PLOOP=$tploop
fi

### If we did not pass any (-q) QUIET options then go verbose
if [ -n "$opt_q" ];
then
### Do something if TRUE, like save the -q input
###echo "Valid var opt_q=$opt_q, use it"
VERBOSE=0
else
### Do something if FALSE, like assign the Global var or a temp Verbose
###echo "Try if global VERBOSE=$VERBOSE, else set to VERBOSE"
[ "$VERBOSE" ] || VERBOSE=$tverbose
fi

### debug ###
#.#echo "mgwy " $MGWY
#.#echo "ploop " $PLOOP
#.#echo "verbose " $VERBOSE
### debug ###

### OK, we have all our inputs, lets go to work.
### Setup if Quiet or Verbose. Output logic: NON-VERBOSE = 0 , VERBOSE = 1 (default)
########### WARNING ###########
# DO NOT run this in the /usr/local/etc/rcS with output enabled
# If using as a local script may use -q or not, in rcS, wse -q
########### WARNING ###########

### Make a redirect command for output (if verbose or not)
redir_cmd() { 
### Are we verbose(1) or quiet(0)
if [ "$VERBOSE" -eq 0 ];
then 
"$@" > /dev/null 
else 
"$@" 
fi 
}

### Lets get started - Define a pinger function and then test if target host IP up
# If network up, exit with status 0, otherwise exit with status 100 (failed)
#redir_cmd echo "Target IP = "$MGWY
# Create awk function to use extended busybox ping with cnt feature
## If your version of native awk is broken, use the version in the package directory
##/usr/local/bin/package/awk ' function pinger(count,ip) {
awk ' function pinger(count,ip) {
command = "'$MBB' ping -c "count " " ip
while (( command | getline res )> 0 ) {
if ( res ~ /0 received|100% packet loss/ ) {
close(command)
return 100
} # IF packet loss
} # WHILE ping
close(command)
return 0
} # FUNCTION pinger
BEGIN { 
IP="'$MGWY'" # Identify the target host
VERB="'$VERBOSE'" # Verbose?
looper='$PLOOP' # how many iterations to test
if ( VERB == 1 ) { print "Checking host " IP " for " looper " iterations, or unless up" }
if ( pinger(2,IP) == 100 ) {
if ( VERB == 1 ) { printf IP " Not up.." }
c = 0
while ( c < looper ) { # we were not up on first pass, keep trying
if ( pinger(2,IP) == 100 ) {
c=c+1
#if ( VERB == 1 ) { print IP " Not up yet." }
if ( VERB == 1 ) { printf " Not up.." }
} else 
{ if ( VERB == 1 ) { print IP " up." }
c=looper
exit 0} # We are up now, so stop while and set exit status
} # While
exit 100 # We are still down
} else { 
if ( VERB == 1 ) { print IP " up." } 
exit 0 } # If the first pass is good, then we are up
} # BEGIN function pinger begin
END {
if ( VERB == 1 ) { print "Exiting. " $0 }
} # END function pinger end
' # awk end
# Were done here -- How did we do - If 0, then network UP, if 100, then network DOWN
##End chknet



Continued in next post.
Mr. Gadget
05-21-2012, 05:57 PM
Part 3, Utility Files

File: getTime


File: getTime.sh

#!/bin/sh
# Date: 20110627 V1.0
# Date: 20110804 V3.1
# Date: 20110804 V3.1b - Change loation for NO HDD - USB only
tver="3.1b"
# By: Mr. Gadget
# Script: getTime [-q]
# Option:
# -q quietmode, no output reported
# Status: 0 = success, 1 = invalid input, 2 = missing Busybox, 100 = network down
#
# This script will set the PBO clock using the updated BusyBox (V1.18) command parser
# with the NTPD feature. Use options for verbose on or off.
# Get the advanced Busybox here (save with extension .asc)
# http://busybox.net/downloads/binaries/1.16.1/busybox-mipsel
# Tip: Make an alias in /etc/profile, 
# alias bb="/tmp/hdd/volumes/HDD1/bin/busybox-mipsel.asc"
# for ongoing use of the advanced busybox commands for interactive use.
# Be sure to modify /etc/profile with your proper TZ (timezone) too.
# Example: TZ='MST7MDT6,J72,J310'

# USER-SPECIFICS
### use either the global exported MGWY or this temp gateway assignment.
# Define your Gateway-Router IP address
tmgwy="192.168.1.253"

# Use can also use prog setMGWY to define variable for your Default Gateway
#echo "Try if global MGWY=$MGWY, else set to temp gateway"
# Which gateway assignment, check if global variable available, else use local
[ "$MGWY" ] || MGWY="$tmgwy"
### echo "MGWY is " $MGWY

# Choices for file locations of your binaries:
# Internal HDD Small partition /tmp/hdd/root (part3 = 512MB, type ext3)
# Internal HDD Large partition /tmp/hdd/volumes/HDD1 (part1 = 500GB, type ufsd)
# Removable USB Rear /tmp/usbmounts/sdb1 (host3 part1 = 8GB, type vfat)
# Removable USB Front /tmp/usbmounts/sda1 (UNUSED)
# Define where your updated BusyBox image is located (not Flash)
# I use the bin folder on the USB (for quick removal/bypass capbility)
#MBB="/tmp/hdd/volumes/HDD1/bin/busybox-mipsel.asc"
#MBB="/tmp/hdd/volumes/HDD1/bin/busybox1.18.3.asc"
MBB="/tmp/usbmounts/sdb1/bin/busybox1.18.3.asc"
CKNET="/tmp/usbmounts/sdb1/bin/scripts/chknet"
# END USER-SPECIFICS

### Test if input options specified
args=`getopt qh $*`
if test $? != 0
then
echo 'Version: '$tver;\
echo 'Usage: '$0' [OPTIONS]'; echo '';\
echo 'Options:'; echo ' -q Quiet mode.'
exit 1
fi

### We may or may not have input, set the arguments
#.#echo "Args are: " $args
set -- $args

### Parse out the arguments, and shift as required.
for i
do
case "$i" in
-q) opt_q=$1;shift;;
-h) echo ''; \
echo 'getTime Version: '$tver;\
echo 'Usage: '$0' [OPTIONS]'; echo '';\
echo 'Options:'; echo ' -q Quiet mode.'
exit 1
esac
done

### If we did not pass any (-q) quite options, make it verbose.
if [ -n "$opt_q" ];
then
### Do something if TRUE, like save the -q input
###echo "Valid var opt_q=$opt_q, use it"
## Be real quiet
VERBOSE=0
##echo "I need to be quiet"
else
### Do something if FALSE
VERBOSE=1
##echo "I can be verbose"
fi

# Make a redirect command for output
redir_cmd() { 
# Are we verbose or not (set busybox ntpd verbose -d option too)
if [ "$VERBOSE" -eq 0 ];
then 
NTPV="-nq"
"$@" > /dev/null 
else 
NTPV="-dnq"
"$@" 
fi 
}

# Start:
# First verify the network is up before we try to get the time.
# Validate acccess to your Router-Gateway MGWY.
redir_cmd echo "Setting the clock from NTP"
# Wait for the network to come up before we access the network

$CKNET -i $MGWY -c 3 -q

# Save the exit status of last command
status=$?
if [ $status -eq 0 ];
then
# Do something if network is UP
# Network is up, how about setting the clock, 
# oh, check to see if we have access to a good BusyBox image
#
if [ -s $MBB ]; then
# File is good, Get time from NTP.ORG
$MBB ntpd $NTPV -p pool.ntp.org
redir_cmd date
exit 0
else
# File not found - better get it right!
redir_cmd echo "File $MBB not found"
exit 2
fi
redir_cmd echo "Done"
else
# Do something if network is DOWN
redir_cmd echo "Network not running. Time not set."
exit 100
fi 

# end getTime


If you want to see myMount.sh, let me know (it also uses chknet to see if network is up, then mount shares).
jamaroney
05-21-2012, 06:27 PM
I'll check this all out - thanks!!
jamaroney
05-22-2012, 12:45 PM
I tried the simple approach: I placed the "ntpd -nq -p pool.ntp.org" command at the very end of the rcS script, immediately preceded by "sleep 30".

For now, that seems to be working well for my setup.
Mr. Gadget
05-22-2012, 03:24 PM
Good to hear it works for you. 
Just a word of caution, if the network is not operational for any reason (using PBO in hotel, on the road...), some commands may not allow your PBO to boot completely (if you are waiting for the network). Be sure to test your commands in various situations if you plan to take it on the road.



list of timezone

원문 : http://en.wikipedia.org/wiki/List_of_tz_database_time_zones

List of tz database time zones

From Wikipedia, the free encyclopedia
World map showing time zones from the tz database version 2009r

This is a list of time zones in the tz database release 2012c. The list is derived from the zones, links, and rules specified in zone.tab and the 7 "continent files" – africaantarcticaasiaaustralasia,europenorthamerica, and southamerica.

The four columns in zone.tab are mapped into columns 1–4 (marked with *) in the table below. The file contains the following comments:

# This file contains a table with the following columns:
# 1.  ISO 3166 2-character country code.  See the file `iso3166.tab'.
# 2.  Latitude and longitude of the zone's principal location
#     in ISO 6709 sign-degrees-minutes-seconds format,
#     either +-DDMM+-DDDMM or +-DDMMSS+-DDDMMSS,
#     first latitude (+ is north), then longitude (+ is east).
# 3.  Zone name used in value of TZ environment variable.
# 4.  Comments; present if and only if the country has multiple rows.

The UTC offsets (columns 5 and 6) are parsed from the "continent files" and are in the format {+|-}hh:mm where the sign is + for east of UTC or - for west of UTC, and hh and mm are hours and minutes, respectively. The UTC DST offset is different from the UTC offset for zones where daylight saving time is observed (see individual time zone pages for details).

The table is sorted by TZ by default.

List[edit]

CC*Coordinates*TZ*Comments*UTC offsetUTC DST offsetNotes
CI+0519-00402Africa/Abidjan+00:00+00:00
GH+0533-00013Africa/Accra+00:00+00:00
ET+0902+03842Africa/Addis_Ababa+03:00+03:00
DZ+3647+00303Africa/Algiers+01:00+01:00
ER+1520+03853Africa/Asmara+03:00+03:00
Africa/Asmera+03:00+03:00Link to Africa/Asmara
ML+1239-00800Africa/Bamako+00:00+00:00
CF+0422+01835Africa/Bangui+01:00+01:00
GM+1328-01639Africa/Banjul+00:00+00:00
GW+1151-01535Africa/Bissau+00:00+00:00
MW-1547+03500Africa/Blantyre+02:00+02:00
CG-0416+01517Africa/Brazzaville+01:00+01:00
BI-0323+02922Africa/Bujumbura+02:00+02:00
EG+3003+03115Africa/Cairo+02:00+02:00DST has been canceled since 2011
MA+3339-00735Africa/Casablanca+00:00+01:00
ES+3553-00519Africa/CeutaCeuta & Melilla+01:00+02:00
GN+0931-01343Africa/Conakry+00:00+00:00
SN+1440-01726Africa/Dakar+00:00+00:00
TZ-0648+03917Africa/Dar_es_Salaam+03:00+03:00
DJ+1136+04309Africa/Djibouti+03:00+03:00
CM+0403+00942Africa/Douala+01:00+01:00
EH+2709-01312Africa/El_Aaiun+00:00+00:00
SL+0830-01315Africa/Freetown+00:00+00:00
BW-2439+02555Africa/Gaborone+02:00+02:00
ZW-1750+03103Africa/Harare+02:00+02:00
ZA-2615+02800Africa/Johannesburg+02:00+02:00
SS+0451+03136Africa/Juba+03:00+03:00
UG+0019+03225Africa/Kampala+03:00+03:00
SD+1536+03232Africa/Khartoum+03:00+03:00
RW-0157+03004Africa/Kigali+02:00+02:00
CD-0418+01518Africa/Kinshasawest Dem. Rep. of Congo+01:00+01:00
NG+0627+00324Africa/Lagos+01:00+01:00
GA+0023+00927Africa/Libreville+01:00+01:00
TG+0608+00113Africa/Lome+00:00+00:00
AO-0848+01314Africa/Luanda+01:00+01:00
CD-1140+02728Africa/Lubumbashieast Dem. Rep. of Congo+02:00+02:00
ZM-1525+02817Africa/Lusaka+02:00+02:00
GQ+0345+00847Africa/Malabo+01:00+01:00
MZ-2558+03235Africa/Maputo+02:00+02:00
LS-2928+02730Africa/Maseru+02:00+02:00
SZ-2618+03106Africa/Mbabane+02:00+02:00
SO+0204+04522Africa/Mogadishu+03:00+03:00
LR+0618-01047Africa/Monrovia+00:00+00:00
KE-0117+03649Africa/Nairobi+03:00+03:00
TD+1207+01503Africa/Ndjamena+01:00+01:00
NE+1331+00207Africa/Niamey+01:00+01:00
MR+1806-01557Africa/Nouakchott+00:00+00:00
BF+1222-00131Africa/Ouagadougou+00:00+00:00
BJ+0629+00237Africa/Porto-Novo+01:00+01:00
ST+0020+00644Africa/Sao_Tome+00:00+00:00
Africa/Timbuktu+00:00+00:00Link to Africa/Bamako
LY+3254+01311Africa/Tripoli+02:00+02:00
TN+3648+01011Africa/Tunis+01:00+01:00
NA-2234+01706Africa/Windhoek+01:00+02:00
AKST9AKDT−09:00−08:00Link to America/Anchorage
US+515248-1763929America/AdakAleutian Islands−10:00−09:00
US+611305-1495401America/AnchorageAlaska Time−09:00−08:00
AI+1812-06304America/Anguilla−04:00−04:00
AG+1703-06148America/Antigua−04:00−04:00
BR-0712-04812America/AraguainaTocantins−03:00−03:00
AR-3436-05827America/Argentina/Buenos_AiresBuenos Aires (BA, CF)−03:00−03:00
AR-2828-06547America/Argentina/CatamarcaCatamarca (CT), Chubut (CH)−03:00−03:00
America/Argentina/ComodRivadavia−03:00−03:00Link toAmerica/Argentina/Catamarca
AR-3124-06411America/Argentina/Cordobamost locations (CB, CC, CN, ER, FM, MN, SE, SF)−03:00−03:00
AR-2411-06518America/Argentina/JujuyJujuy (JY)−03:00−03:00
AR-2926-06651America/Argentina/La_RiojaLa Rioja (LR)−03:00−03:00
AR-3253-06849America/Argentina/MendozaMendoza (MZ)−03:00−03:00
AR-5138-06913America/Argentina/Rio_GallegosSanta Cruz (SC)−03:00−03:00
AR-2447-06525America/Argentina/Salta(SA, LP, NQ, RN)−03:00−03:00
AR-3132-06831America/Argentina/San_JuanSan Juan (SJ)−03:00−03:00
AR-3319-06621America/Argentina/San_LuisSan Luis (SL)−03:00−03:00
AR-2649-06513America/Argentina/TucumanTucuman (TM)−03:00−03:00
AR-5448-06818America/Argentina/UshuaiaTierra del Fuego (TF)−03:00−03:00
AW+1230-06958America/Aruba−04:00−04:00
PY-2516-05740America/Asuncion−04:00−03:00
CA+484531-0913718America/AtikokanEastern Standard Time - Atikokan, Ontario and Southampton I, Nunavut−05:00−05:00
America/Atka−10:00−09:00Link to America/Adak
BR-1259-03831America/BahiaBahia−03:00−02:00
MX+2048-10515America/Bahia_BanderasMexican Central Time - Bahia de Banderas−06:00−05:00
BB+1306-05937America/Barbados−04:00−04:00
BR-0127-04829America/BelemAmapa, E Para−03:00−03:00
BZ+1730-08812America/Belize−06:00−06:00
CA+5125-05707America/Blanc-SablonAtlantic Standard Time - Quebec - Lower North Shore−04:00−04:00
BR+0249-06040America/Boa_VistaRoraima−04:00−04:00
CO+0436-07405America/Bogota−05:00−05:00
US+433649-1161209America/BoiseMountain Time - south Idaho & east Oregon−07:00−06:00
America/Buenos_Aires−03:00−03:00Link toAmerica/Argentina/Buenos_Aires
CA+690650-1050310America/Cambridge_BayMountain Time - west Nunavut−07:00−06:00
BR-2027-05437America/Campo_GrandeMato Grosso do Sul−04:00−03:00
MX+2105-08646America/CancunCentral Time - Quintana Roo−06:00−05:00
VE+1030-06656America/Caracas−04:30−04:30
America/Catamarca−03:00−03:00Link toAmerica/Argentina/Catamarca
GF+0456-05220America/Cayenne−03:00−03:00
KY+1918-08123America/Cayman−05:00−05:00
US+415100-0873900America/ChicagoCentral Time−06:00−05:00
MX+2838-10605America/ChihuahuaMexican Mountain Time - Chihuahua away from US border−07:00−06:00
America/Coral_Harbour−05:00−05:00Link to America/Atikokan
America/Cordoba−03:00−03:00Link toAmerica/Argentina/Cordoba
CR+0956-08405America/Costa_Rica−06:00−06:00
CA+4906-11631America/CrestonMountain Standard Time - Creston, British Columbia−07:00−07:00
BR-1535-05605America/CuiabaMato Grosso−04:00−03:00
CW+1211-06900America/Curacao−04:00−04:00
GL+7646-01840America/Danmarkshavneast coast, north of Scoresbysund+00:00+00:00
CA+6404-13925America/DawsonPacific Time - north Yukon−08:00−07:00
CA+5946-12014America/Dawson_CreekMountain Standard Time - Dawson Creek & Fort Saint John, British Columbia−07:00−07:00
US+394421-1045903America/DenverMountain Time−07:00−06:00
US+421953-0830245America/DetroitEastern Time - Michigan - most locations−05:00−04:00
DM+1518-06124America/Dominica−04:00−04:00
CA+5333-11328America/EdmontonMountain Time - Alberta, east British Columbia & west Saskatchewan−07:00−06:00
BR-0640-06952America/EirunepeW Amazonas−04:00−04:00
SV+1342-08912America/El_Salvador−06:00−06:00
America/Ensenada−08:00−07:00Link to America/Tijuana
America/Fort_Wayne−05:00−04:00Link toAmerica/Indiana/Indianapolis
BR-0343-03830America/FortalezaNE Brazil (MA, PI, CE, RN, PB)−03:00−03:00
CA+4612-05957America/Glace_BayAtlantic Time - Nova Scotia - places that did not observe DST 1966-1971−04:00−03:00
GL+6411-05144America/Godthabmost locations−03:00−02:00
CA+5320-06025America/Goose_BayAtlantic Time - Labrador - most locations−04:00−03:00
TC+2128-07108America/Grand_Turk−05:00−04:00
GD+1203-06145America/Grenada−04:00−04:00
GP+1614-06132America/Guadeloupe−04:00−04:00
GT+1438-09031America/Guatemala−06:00−06:00
EC-0210-07950America/Guayaquilmainland−05:00−05:00
GY+0648-05810America/Guyana−04:00−04:00
CA+4439-06336America/HalifaxAtlantic Time - Nova Scotia (most places), PEI−04:00−03:00
CU+2308-08222America/Havana−05:00−04:00
MX+2904-11058America/HermosilloMountain Standard Time - Sonora−07:00−07:00
US+394606-0860929America/Indiana/IndianapolisEastern Time - Indiana - most locations−05:00−04:00
US+411745-0863730America/Indiana/KnoxCentral Time - Indiana - Starke County−06:00−05:00
US+382232-0862041America/Indiana/MarengoEastern Time - Indiana - Crawford County−05:00−04:00
US+382931-0871643America/Indiana/PetersburgEastern Time - Indiana - Pike County−05:00−04:00
US+375711-0864541America/Indiana/Tell_CityCentral Time - Indiana - Perry County−06:00−05:00
US+384452-0850402America/Indiana/VevayEastern Time - Indiana - Switzerland County−05:00−04:00
US+384038-0873143America/Indiana/VincennesEastern Time - Indiana - Daviess, Dubois, Knox & Martin Counties−05:00−04:00
US+410305-0863611America/Indiana/WinamacEastern Time - Indiana - Pulaski County−05:00−04:00
America/Indianapolis−05:00−04:00Link toAmerica/Indiana/Indianapolis
CA+682059-1334300America/InuvikMountain Time - west Northwest Territories−07:00−06:00
CA+6344-06828America/IqaluitEastern Time - east Nunavut - most locations−05:00−04:00
JM+1800-07648America/Jamaica−05:00−05:00
America/Jujuy−03:00−03:00Link to America/Argentina/Jujuy
US+581807-1342511America/JuneauAlaska Time - Alaska panhandle−09:00−08:00
US+381515-0854534America/Kentucky/LouisvilleEastern Time - Kentucky - Louisville area−05:00−04:00
US+364947-0845057America/Kentucky/MonticelloEastern Time - Kentucky - Wayne County−05:00−04:00
America/Knox_IN−06:00−05:00Link to America/Indiana/Knox
BQ+120903-0681636America/Kralendijk−04:00−04:00Link to America/Curacao
BO-1630-06809America/La_Paz−04:00−04:00
PE-1203-07703America/Lima−05:00−05:00
US+340308-1181434America/Los_AngelesPacific Time−08:00−07:00
America/Louisville−05:00−04:00Link toAmerica/Kentucky/Louisville
SX+180305-0630250America/Lower_Princes−04:00−04:00Link to America/Curacao
BR-0940-03543America/MaceioAlagoas, Sergipe−03:00−03:00
NI+1209-08617America/Managua−06:00−06:00
BR-0308-06001America/ManausE Amazonas−04:00−04:00
MF+1804-06305America/Marigot−04:00−04:00Link to America/Guadeloupe
MQ+1436-06105America/Martinique−04:00−04:00
MX+2550-09730America/MatamorosUS Central Time - Coahuila, Durango, Nuevo Leon, Tamaulipas near US border−06:00−05:00
MX+2313-10625America/MazatlanMountain Time - S Baja, Nayarit, Sinaloa−07:00−06:00
America/Mendoza−03:00−03:00Link toAmerica/Argentina/Mendoza
US+450628-0873651America/MenomineeCentral Time - Michigan - Dickinson, Gogebic, Iron & Menominee Counties−06:00−05:00
MX+2058-08937America/MeridaCentral Time - Campeche, Yucatan−06:00−05:00
US+550737-1313435America/MetlakatlaMetlakatla Time - Annette Island−08:00−08:00
MX+1924-09909America/Mexico_CityCentral Time - most locations−06:00−05:00
PM+4703-05620America/Miquelon−03:00−02:00
CA+4606-06447America/MonctonAtlantic Time - New Brunswick−04:00−03:00
MX+2540-10019America/MonterreyMexican Central Time - Coahuila, Durango, Nuevo Leon, Tamaulipas away from US border−06:00−05:00
UY-3453-05611America/Montevideo−03:00−02:00
CA+4531-07334America/MontrealEastern Time - Quebec - most locations−05:00−04:00
MS+1643-06213America/Montserrat−04:00−04:00
BS+2505-07721America/Nassau−05:00−04:00
US+404251-0740023America/New_YorkEastern Time−05:00−04:00
CA+4901-08816America/NipigonEastern Time - Ontario & Quebec - places that did not observe DST 1967-1973−05:00−04:00
US+643004-1652423America/NomeAlaska Time - west Alaska−09:00−08:00
BR-0351-03225America/NoronhaAtlantic islands−02:00−02:00
US+471551-1014640America/North_Dakota/BeulahCentral Time - North Dakota - Mercer County−06:00−05:00
US+470659-1011757America/North_Dakota/CenterCentral Time - North Dakota - Oliver County−06:00−05:00
US+465042-1012439America/North_Dakota/New_SalemCentral Time - North Dakota - Morton County (except Mandan area)−06:00−05:00
MX+2934-10425America/OjinagaUS Mountain Time - Chihuahua near US border−07:00−06:00
PA+0858-07932America/Panama−05:00−05:00
CA+6608-06544America/PangnirtungEastern Time - Pangnirtung, Nunavut−05:00−04:00
SR+0550-05510America/Paramaribo−03:00−03:00
US+332654-1120424America/PhoenixMountain Standard Time - Arizona−07:00−07:00
TT+1039-06131America/Port_of_Spain−04:00−04:00
HT+1832-07220America/Port-au-Prince−05:00−04:00
America/Porto_Acre−04:00−04:00Link to America/Rio_Branco
BR-0846-06354America/Porto_VelhoRondonia−04:00−04:00
PR+182806-0660622America/Puerto_Rico−04:00−04:00
CA+4843-09434America/Rainy_RiverCentral Time - Rainy River & Fort Frances, Ontario−06:00−05:00
CA+624900-0920459America/Rankin_InletCentral Time - central Nunavut−06:00−05:00
BR-0803-03454America/RecifePernambuco−03:00−03:00
CA+5024-10439America/ReginaCentral Standard Time - Saskatchewan - most locations−06:00−06:00
CA+744144-0944945America/ResoluteCentral Standard Time - Resolute, Nunavut−06:00−05:00
BR-0958-06748America/Rio_BrancoAcre−04:00−04:00
America/Rosario−03:00−03:00Link toAmerica/Argentina/Cordoba
MX+3018-11452America/Santa_IsabelMexican Pacific Time - Baja California away from US border−08:00−07:00
BR-0226-05452America/SantaremW Para−03:00−03:00
CL-3327-07040America/Santiagomost locations−04:00−03:00
DO+1828-06954America/Santo_Domingo−04:00−04:00
BR-2332-04637America/Sao_PauloS & SE Brazil (GO, DF, MG, ES, RJ, SP, PR, SC, RS)−03:00−02:00
GL+7029-02158America/ScoresbysundScoresbysund / Ittoqqortoormiit−01:00+00:00
US+364708-1084111America/ShiprockMountain Time - Navajo−07:00−06:00Link to America/Denver
US+571035-1351807America/SitkaAlaska Time - southeast Alaska panhandle−09:00−08:00
BL+1753-06251America/St_Barthelemy−04:00−04:00Link to America/Guadeloupe
CA+4734-05243America/St_JohnsNewfoundland Time, including SE Labrador−03:30−02:30
KN+1718-06243America/St_Kitts−04:00−04:00
LC+1401-06100America/St_Lucia−04:00−04:00
VI+1821-06456America/St_Thomas−04:00−04:00
VC+1309-06114America/St_Vincent−04:00−04:00
CA+5017-10750America/Swift_CurrentCentral Standard Time - Saskatchewan - midwest−06:00−06:00
HN+1406-08713America/Tegucigalpa−06:00−06:00
GL+7634-06847America/ThuleThule / Pituffik−04:00−03:00
CA+4823-08915America/Thunder_BayEastern Time - Thunder Bay, Ontario−05:00−04:00
MX+3232-11701America/TijuanaUS Pacific Time - Baja California near US border−08:00−07:00
CA+4339-07923America/TorontoEastern Time - Ontario - most locations−05:00−04:00
VG+1827-06437America/Tortola−04:00−04:00
CA+4916-12307America/VancouverPacific Time - west British Columbia−08:00−07:00
America/Virgin−04:00−04:00Link to America/St_Thomas
CA+6043-13503America/WhitehorsePacific Time - south Yukon−08:00−07:00
CA+4953-09709America/WinnipegCentral Time - Manitoba & west Ontario−06:00−05:00
US+593249-1394338America/YakutatAlaska Time - Alaska panhandle neck−09:00−08:00
CA+6227-11421America/YellowknifeMountain Time - central Northwest Territories−07:00−06:00
AQ-6617+11031Antarctica/CaseyCasey Station, Bailey Peninsula+11:00+08:00
AQ-6835+07758Antarctica/DavisDavis Station, Vestfold Hills+05:00+07:00
AQ-6640+14001Antarctica/DumontDUrvilleDumont-d'Urville Station, Terre Adelie+10:00+10:00
AQ-5430+15857Antarctica/MacquarieMacquarie Island Station, Macquarie Island+11:00+11:00
AQ-6736+06253Antarctica/MawsonMawson Station, Holme Bay+05:00+05:00
AQ-7750+16636Antarctica/McMurdoMcMurdo Station, Ross Island+12:00+13:00
AQ-6448-06406Antarctica/PalmerPalmer Station, Anvers Island−04:00−03:00
AQ-6734-06808Antarctica/RotheraRothera Station, Adelaide Island−03:00−03:00
AQ-9000+00000Antarctica/South_PoleAmundsen-Scott Station, South Pole+12:00+13:00Link to Antarctica/McMurdo
AQ-690022+0393524Antarctica/SyowaSyowa Station, E Ongul I+03:00+03:00
AQ-7824+10654Antarctica/VostokVostok Station, Lake Vostok+06:00+06:00
SJ+7800+01600Arctic/Longyearbyen+01:00+02:00Link to Europe/Oslo
YE+1245+04512Asia/Aden+03:00+03:00
KZ+4315+07657Asia/Almatymost locations+06:00+06:00
JO+3157+03556Asia/Amman+02:00+03:00
RU+6445+17729Asia/AnadyrMoscow+08 - Bering Sea+12:00+12:00
KZ+4431+05016Asia/AqtauAtyrau (Atirau, Gur'yev), Mangghystau (Mankistau)+05:00+05:00
KZ+5017+05710Asia/AqtobeAqtobe (Aktobe)+05:00+05:00
TM+3757+05823Asia/Ashgabat+05:00+05:00
Asia/Ashkhabad+05:00+05:00Link to Asia/Ashgabat
IQ+3321+04425Asia/Baghdad+03:00+03:00
BH+2623+05035Asia/Bahrain+03:00+03:00
AZ+4023+04951Asia/Baku+04:00+05:00
TH+1345+10031Asia/Bangkok+07:00+07:00
LB+3353+03530Asia/Beirut+02:00+03:00
KG+4254+07436Asia/Bishkek+06:00+06:00
BN+0456+11455Asia/Brunei+08:00+08:00
Asia/Calcutta+05:30+05:30Link to Asia/Kolkata
MN+4804+11430Asia/ChoibalsanDornod, Sukhbaatar+08:00+08:00
CN+2934+10635Asia/Chongqingcentral China - Sichuan, Yunnan, Guangxi, Shaanxi, Guizhou, etc.+08:00+08:00Covering historic Kansu-Szechuan time zone.
Asia/Chungking+08:00+08:00Link to Asia/Chongqing
LK+0656+07951Asia/Colombo+05:30+05:30
Asia/Dacca+06:00+06:00Link to Asia/Dhaka
SY+3330+03618Asia/Damascus+02:00+03:00
BD+2343+09025Asia/Dhaka+06:00+06:00
TL-0833+12535Asia/Dili+09:00+09:00
AE+2518+05518Asia/Dubai+04:00+04:00
TJ+3835+06848Asia/Dushanbe+05:00+05:00
PS+3130+03428Asia/GazaGaza Strip+02:00+03:00
CN+4545+12641Asia/HarbinHeilongjiang (except Mohe), Jilin+08:00+08:00Covering historic Changpai time zone.
PS+313200+0350542Asia/HebronWest Bank+02:00+03:00
VN+1045+10640Asia/Ho_Chi_Minh+07:00+07:00
HK+2217+11409Asia/Hong_Kong+08:00+08:00
MN+4801+09139Asia/HovdBayan-Olgiy, Govi-Altai, Hovd, Uvs, Zavkhan+07:00+07:00
RU+5216+10420Asia/IrkutskMoscow+05 - Lake Baikal+09:00+09:00
Asia/Istanbul+02:00+03:00Link to Europe/Istanbul
ID-0610+10648Asia/JakartaJava & Sumatra+07:00+07:00
ID-0232+14042Asia/Jayapurawest New Guinea (Irian Jaya) & Malukus (Moluccas)+09:00+09:00
IL+3146+03514Asia/Jerusalem+02:00+03:00
AF+3431+06912Asia/Kabul+04:30+04:30
RU+5301+15839Asia/KamchatkaMoscow+08 - Kamchatka+12:00+12:00
PK+2452+06703Asia/Karachi+05:00+05:00
CN+3929+07559Asia/Kashgarwest Tibet & Xinjiang+08:00+08:00Covering historic Kunlun time zone.
NP+2743+08519Asia/Kathmandu+05:45+05:45
Asia/Katmandu+05:45+05:45Link to Asia/Kathmandu
IN+2232+08822Asia/Kolkata+05:30+05:30Note: Different zones in history, see Time in India.
RU+5601+09250Asia/KrasnoyarskMoscow+04 - Yenisei River+08:00+08:00
MY+0310+10142Asia/Kuala_Lumpurpeninsular Malaysia+08:00+08:00
MY+0133+11020Asia/KuchingSabah & Sarawak+08:00+08:00
KW+2920+04759Asia/Kuwait+03:00+03:00
Asia/Macao+08:00+08:00Link to Asia/Macau
MO+2214+11335Asia/Macau+08:00+08:00
RU+5934+15048Asia/MagadanMoscow+08 - Magadan+12:00+12:00
ID-0507+11924Asia/Makassareast & south Borneo, Sulawesi (Celebes), Bali, Nusa Tengarra, west Timor+08:00+08:00
PH+1435+12100Asia/Manila+08:00+08:00
OM+2336+05835Asia/Muscat+04:00+04:00
CY+3510+03322Asia/Nicosia+02:00+03:00
RU+5345+08707Asia/NovokuznetskMoscow+03 - Novokuznetsk+07:00+07:00
RU+5502+08255Asia/NovosibirskMoscow+03 - Novosibirsk+07:00+07:00
RU+5500+07324Asia/OmskMoscow+03 - west Siberia+07:00+07:00
KZ+5113+05121Asia/OralWest Kazakhstan+05:00+05:00
KH+1133+10455Asia/Phnom_Penh+07:00+07:00
ID-0002+10920Asia/Pontianakwest & central Borneo+07:00+07:00
KP+3901+12545Asia/Pyongyang+09:00+09:00
QA+2517+05132Asia/Qatar+03:00+03:00
KZ+4448+06528Asia/QyzylordaQyzylorda (Kyzylorda, Kzyl-Orda)+06:00+06:00
MM+1647+09610Asia/Rangoon+06:30+06:30
SA+2438+04643Asia/Riyadh+03:00+03:00
Asia/Saigon+07:00+07:00Link to Asia/Ho_Chi_Minh
RU+4658+14242Asia/SakhalinMoscow+07 - Sakhalin Island+11:00+11:00
UZ+3940+06648Asia/Samarkandwest Uzbekistan+05:00+05:00
KR+3733+12658Asia/Seoul+09:00+09:00
CN+3114+12128Asia/Shanghaieast China - Beijing, Guangdong, Shanghai, etc.+08:00+08:00Covering historic Chungyuan time zone.
SG+0117+10351Asia/Singapore+08:00+08:00
TW+2503+12130Asia/Taipei+08:00+08:00
UZ+4120+06918Asia/Tashkenteast Uzbekistan+05:00+05:00
GE+4143+04449Asia/Tbilisi+04:00+04:00
IR+3540+05126Asia/Tehran+03:30+04:30
Asia/Tel_Aviv+02:00+03:00Link to Asia/Jerusalem
Asia/Thimbu+06:00+06:00Link to Asia/Thimphu
BT+2728+08939Asia/Thimphu+06:00+06:00
JP+353916+1394441Asia/Tokyo+09:00+09:00
Asia/Ujung_Pandang+08:00+08:00Link to Asia/Makassar
MN+4755+10653Asia/Ulaanbaatarmost locations+08:00+08:00
Asia/Ulan_Bator+08:00+08:00Link to Asia/Ulaanbaatar
CN+4348+08735Asia/Urumqimost of Tibet & Xinjiang+08:00+08:00Covering historic Sinkiang-Tibettime zone.
LA+1758+10236Asia/Vientiane+07:00+07:00
RU+4310+13156Asia/VladivostokMoscow+07 - Amur River+11:00+11:00
RU+6200+12940Asia/YakutskMoscow+06 - Lena River+10:00+10:00
RU+5651+06036Asia/YekaterinburgMoscow+02 - Urals+06:00+06:00
AM+4011+04430Asia/Yerevan+04:00+04:00
PT+3744-02540Atlantic/AzoresAzores−01:00+00:00
BM+3217-06446Atlantic/Bermuda−04:00−03:00
ES+2806-01524Atlantic/CanaryCanary Islands+00:00+01:00
CV+1455-02331Atlantic/Cape_Verde−01:00−01:00
Atlantic/Faeroe+00:00+01:00Link to Atlantic/Faroe
FO+6201-00646Atlantic/Faroe+00:00+01:00
Atlantic/Jan_Mayen+01:00+02:00Link to Europe/Oslo
PT+3238-01654Atlantic/MadeiraMadeira Islands+00:00+01:00
IS+6409-02151Atlantic/Reykjavik+00:00+00:00
GS-5416-03632Atlantic/South_Georgia−02:00−02:00
SH-1555-00542Atlantic/St_Helena+00:00+00:00
FK-5142-05751Atlantic/Stanley−03:00−03:00
Australia/ACT+10:00+11:00Link to Australia/Sydney
AU-3455+13835Australia/AdelaideSouth Australia+09:30+10:30
AU-2728+15302Australia/BrisbaneQueensland - most locations+10:00+10:00
AU-3157+14127Australia/Broken_HillNew South Wales - Yancowinna+09:30+10:30
Australia/Canberra+10:00+11:00Link to Australia/Sydney
AU-3956+14352Australia/CurrieTasmania - King Island+10:00+11:00
AU-1228+13050Australia/DarwinNorthern Territory+09:30+09:30
AU-3143+12852Australia/EuclaWestern Australia - Eucla area+08:45+08:45
AU-4253+14719Australia/HobartTasmania - most locations+10:00+11:00
Australia/LHI+10:30+11:00Link to Australia/Lord_Howe
AU-2016+14900Australia/LindemanQueensland - Holiday Islands+10:00+10:00
AU-3133+15905Australia/Lord_HoweLord Howe Island+10:30+11:00
AU-3749+14458Australia/MelbourneVictoria+10:00+11:00
Australia/North+09:30+09:30Link to Australia/Darwin
Australia/NSW+10:00+11:00Link to Australia/Sydney
AU-3157+11551Australia/PerthWestern Australia - most locations+08:00+08:00
Australia/Queensland+10:00+10:00Link to Australia/Brisbane
Australia/South+09:30+10:30Link to Australia/Adelaide
AU-3352+15113Australia/SydneyNew South Wales - most locations+10:00+11:00
Australia/Tasmania+10:00+11:00Link to Australia/Hobart
Australia/Victoria+10:00+11:00Link to Australia/Melbourne
Australia/West+08:00+08:00Link to Australia/Perth
Australia/Yancowinna+09:30+10:30Link to Australia/Broken_Hill
Brazil/Acre−04:00−04:00Link to America/Rio_Branco
Brazil/DeNoronha−02:00−02:00Link to America/Noronha
Brazil/East−03:00−02:00Link to America/Sao_Paulo
Brazil/West−04:00−04:00Link to America/Manaus
Canada/Atlantic−04:00−03:00Link to America/Halifax
Canada/Central−06:00−05:00Link to America/Winnipeg
Canada/Eastern−05:00−04:00Link to America/Toronto
Canada/East-Saskatchewan−06:00−06:00Link to America/Regina
Canada/Mountain−07:00−06:00Link to America/Edmonton
Canada/Newfoundland−03:30−02:30Link to America/St_Johns
Canada/Pacific−08:00−07:00Link to America/Vancouver
Canada/Saskatchewan−06:00−06:00Link to America/Regina
Canada/Yukon−08:00−07:00Link to America/Whitehorse
CET+01:00+02:00
Chile/Continental−04:00−03:00Link to America/Santiago
Chile/EasterIsland−06:00−05:00Link to Pacific/Easter
CST6CDT−06:00−05:00
Cuba−05:00−04:00Link to America/Havana
EET+02:00+03:00
Egypt+02:00+02:00Link to Africa/Cairo
Eire+00:00+01:00Link to Europe/Dublin
EST−05:00−05:00
EST5EDT−05:00−04:00
Etc/GMT+00:00+00:00Link to UTC
Etc/GMT+0+00:00+00:00Link to UTC
Etc/UCT+00:00+00:00Link to UTC
Etc/Universal+00:00+00:00Link to UTC
Etc/UTC+00:00+00:00Link to UTC
Etc/Zulu+00:00+00:00Link to UTC
NL+5222+00454Europe/Amsterdam+01:00+02:00
AD+4230+00131Europe/Andorra+01:00+02:00
GR+3758+02343Europe/Athens+02:00+03:00
Europe/Belfast+00:00+01:00Link to Europe/London
RS+4450+02030Europe/Belgrade+01:00+02:00
DE+5230+01322Europe/Berlin+01:00+02:00In 1945, the Trizone did not follow Berlin's switch to DST, see Time in Germany
SK+4809+01707Europe/Bratislava+01:00+02:00Link to Europe/Prague
BE+5050+00420Europe/Brussels+01:00+02:00
RO+4426+02606Europe/Bucharest+02:00+03:00
HU+4730+01905Europe/Budapest+01:00+02:00
MD+4700+02850Europe/Chisinau+02:00+03:00
DK+5540+01235Europe/Copenhagen+01:00+02:00
IE+5320-00615Europe/Dublin+00:00+01:00
GI+3608-00521Europe/Gibraltar+01:00+02:00
GG+4927-00232Europe/Guernsey+00:00+01:00Link to Europe/London
FI+6010+02458Europe/Helsinki+02:00+03:00
IM+5409-00428Europe/Isle_of_Man+00:00+01:00Link to Europe/London
TR+4101+02858Europe/Istanbul+02:00+03:00
JE+4912-00207Europe/Jersey+00:00+01:00Link to Europe/London
RU+5443+02030Europe/KaliningradMoscow-01 - Kaliningrad+03:00+03:00
UA+5026+03031Europe/Kievmost locations+02:00+03:00
PT+3843-00908Europe/Lisbonmainland+00:00+01:00
SI+4603+01431Europe/Ljubljana+01:00+02:00Link to Europe/Belgrade
GB+513030-0000731Europe/London+00:00+01:00
LU+4936+00609Europe/Luxembourg+01:00+02:00
ES+4024-00341Europe/Madridmainland+01:00+02:00
MT+3554+01431Europe/Malta+01:00+02:00
AX+6006+01957Europe/Mariehamn+02:00+03:00Link to Europe/Helsinki
BY+5354+02734Europe/Minsk+03:00+03:00
MC+4342+00723Europe/Monaco+01:00+02:00
RU+5545+03735Europe/MoscowMoscow+00 - west Russia+04:00+04:00
Europe/Nicosia+02:00+03:00Link to Asia/Nicosia
NO+5955+01045Europe/Oslo+01:00+02:00
FR+4852+00220Europe/Paris+01:00+02:00
ME+4226+01916Europe/Podgorica+01:00+02:00Link to Europe/Belgrade
CZ+5005+01426Europe/Prague+01:00+02:00
LV+5657+02406Europe/Riga+02:00+03:00
IT+4154+01229Europe/Rome+01:00+02:00
RU+5312+05009Europe/SamaraMoscow+00 - Samara, Udmurtia+04:00+04:00
SM+4355+01228Europe/San_Marino+01:00+02:00Link to Europe/Rome
BA+4352+01825Europe/Sarajevo+01:00+02:00Link to Europe/Belgrade
UA+4457+03406Europe/Simferopolcentral Crimea+02:00+03:00
MK+4159+02126Europe/Skopje+01:00+02:00Link to Europe/Belgrade
BG+4241+02319Europe/Sofia+02:00+03:00
SE+5920+01803Europe/Stockholm+01:00+02:00
EE+5925+02445Europe/Tallinn+02:00+03:00
AL+4120+01950Europe/Tirane+01:00+02:00
Europe/Tiraspol+02:00+03:00Link to Europe/Chisinau
UA+4837+02218Europe/UzhgorodRuthenia+02:00+03:00
LI+4709+00931Europe/Vaduz+01:00+02:00
VA+415408+0122711Europe/Vatican+01:00+02:00Link to Europe/Rome
AT+4813+01620Europe/Vienna+01:00+02:00
LT+5441+02519Europe/Vilnius+02:00+03:00
RU+4844+04425Europe/VolgogradMoscow+00 - Caspian Sea+04:00+04:00
PL+5215+02100Europe/Warsaw+01:00+02:00
HR+4548+01558Europe/Zagreb+01:00+02:00Link to Europe/Belgrade
UA+4750+03510Europe/ZaporozhyeZaporozh'ye, E Lugansk / Zaporizhia, E Luhansk+02:00+03:00
CH+4723+00832Europe/Zurich+01:00+02:00
GB+00:00+01:00Link to Europe/London
GB-Eire+00:00+01:00Link to Europe/London
GMT+00:00+00:00Link to UTC
GMT+0+00:00+00:00Link to UTC
GMT0+00:00+00:00Link to UTC
GMT-0+00:00+00:00Link to UTC
Greenwich+00:00+00:00Link to UTC
Hongkong+08:00+08:00Link to Asia/Hong_Kong
HST−10:00−10:00
Iceland+00:00+00:00Link to Atlantic/Reykjavik
MG-1855+04731Indian/Antananarivo+03:00+03:00
IO-0720+07225Indian/Chagos+06:00+06:00
CX-1025+10543Indian/Christmas+07:00+07:00
CC-1210+09655Indian/Cocos+06:30+06:30
KM-1141+04316Indian/Comoro+03:00+03:00
TF-492110+0701303Indian/Kerguelen+05:00+05:00
SC-0440+05528Indian/Mahe+04:00+04:00
MV+0410+07330Indian/Maldives+05:00+05:00
MU-2010+05730Indian/Mauritius+04:00+04:00
YT-1247+04514Indian/Mayotte+03:00+03:00
RE-2052+05528Indian/Reunion+04:00+04:00
Iran+03:30+04:30Link to Asia/Tehran
Israel+02:00+03:00Link to Asia/Jerusalem
Jamaica−05:00−05:00Link to America/Jamaica
Japan+09:00+09:00Link to Asia/Tokyo
JST-9+09:00+09:00Link to Asia/Tokyo
Kwajalein+12:00+12:00Link to Pacific/Kwajalein
Libya+02:00+02:00Link to Africa/Tripoli
MET+01:00+02:00
Mexico/BajaNorte−08:00−07:00Link to America/Tijuana
Mexico/BajaSur−07:00−06:00Link to America/Mazatlan
Mexico/General−06:00−05:00Link to America/Mexico_City
MST−07:00−07:00
MST7MDT−07:00−06:00
Navajo−07:00−06:00Link to America/Denver
NZ+12:00+13:00Link to Pacific/Auckland
NZ-CHAT+12:45+13:45Link to Pacific/Chatham
WS-1350-17144Pacific/Apia+13:00+14:00
NZ-3652+17446Pacific/Aucklandmost locations+12:00+13:00
NZ-4357-17633Pacific/ChathamChatham Islands+12:45+13:45
FM+0725+15147Pacific/ChuukChuuk (Truk) and Yap+10:00+10:00
CL-2709-10926Pacific/EasterEaster Island & Sala y Gomez−06:00−05:00
VU-1740+16825Pacific/Efate+11:00+11:00
KI-0308-17105Pacific/EnderburyPhoenix Islands+13:00+13:00
TK-0922-17114Pacific/Fakaofo+13:00+13:00
FJ-1808+17825Pacific/Fiji+12:00+13:00
TV-0831+17913Pacific/Funafuti+12:00+12:00
EC-0054-08936Pacific/GalapagosGalapagos Islands−06:00−06:00
PF-2308-13457Pacific/GambierGambier Islands−09:00−09:00
SB-0932+16012Pacific/Guadalcanal+11:00+11:00
GU+1328+14445Pacific/Guam+10:00+10:00
US+211825-1575130Pacific/HonoluluHawaii−10:00−10:00
UM+1645-16931Pacific/JohnstonJohnston Atoll−10:00−10:00
KI+0152-15720Pacific/KiritimatiLine Islands+14:00+14:00
FM+0519+16259Pacific/KosraeKosrae+11:00+11:00
MH+0905+16720Pacific/KwajaleinKwajalein+12:00+12:00
MH+0709+17112Pacific/Majuromost locations+12:00+12:00
PF-0900-13930Pacific/MarquesasMarquesas Islands−09:30−09:30
UM+2813-17722Pacific/MidwayMidway Islands−11:00−11:00
NR-0031+16655Pacific/Nauru+12:00+12:00
NU-1901-16955Pacific/Niue−11:00−11:00
NF-2903+16758Pacific/Norfolk+11:30+11:30
NC-2216+16627Pacific/Noumea+11:00+11:00
AS-1416-17042Pacific/Pago_Pago−11:00−11:00
PW+0720+13429Pacific/Palau+09:00+09:00
PN-2504-13005Pacific/Pitcairn−08:00−08:00
FM+0658+15813Pacific/PohnpeiPohnpei (Ponape)+11:00+11:00
Pacific/Ponape+11:00+11:00Link to Pacific/Pohnpei
PG-0930+14710Pacific/Port_Moresby+10:00+10:00
CK-2114-15946Pacific/Rarotonga−10:00−10:00
MP+1512+14545Pacific/Saipan+10:00+10:00
Pacific/Samoa−11:00−11:00Link to Pacific/Pago_Pago
PF-1732-14934Pacific/TahitiSociety Islands−10:00−10:00
KI+0125+17300Pacific/TarawaGilbert Islands+12:00+12:00
TO-2110-17510Pacific/Tongatapu+13:00+13:00
Pacific/Truk+10:00+10:00Link to Pacific/Chuuk
UM+1917+16637Pacific/WakeWake Island+12:00+12:00
WF-1318-17610Pacific/Wallis+12:00+12:00
Pacific/Yap+10:00+10:00Link to Pacific/Chuuk
Poland+01:00+02:00Link to Europe/Warsaw
Portugal+00:00+01:00Link to Europe/Lisbon
PRC+08:00+08:00Link to Asia/Shanghai
PST8PDT−08:00−07:00
ROC+08:00+08:00Link to Asia/Taipei
ROK+09:00+09:00Link to Asia/Seoul
Singapore+08:00+08:00Link to Asia/Singapore
Turkey+02:00+03:00Link to Europe/Istanbul
UCT+00:00+00:00Link to UTC
Universal+00:00+00:00Link to UTC
US/Alaska−09:00−08:00Link to America/Anchorage
US/Aleutian−10:00−09:00Link to America/Adak
US/Arizona−07:00−07:00Link to America/Phoenix
US/Central−06:00−05:00Link to America/Chicago
US/Eastern−05:00−04:00Link to America/New_York
US/East-Indiana−05:00−04:00Link toAmerica/Indiana/Indianapolis
US/Hawaii−10:00−10:00Link to Pacific/Honolulu
US/Indiana-Starke−06:00−05:00Link to America/Indiana/Knox
US/Michigan−05:00−04:00Link to America/Detroit
US/Mountain−07:00−06:00Link to America/Denver
US/Pacific−08:00−07:00Link to America/Los_Angeles
US/Pacific-New−08:00−07:00Link to America/Los_Angeles
US/Samoa−11:00−11:00Link to Pacific/Pago_Pago
UTC+00:00+00:00
WET+00:00+01:00
W-SU+04:00+04:00Link to Europe/Moscow
Zulu+00:00+00:00Link to UTC



Number of zones/links by region
RegionZonesLinksTotal
Africa52254
America14321164
Antarctica10111
Arctic011
Asia771289
Atlantic10212
Australia121123
Europe431558
Indian11011
Pacific38442
Misc127183
Total408140548


Posted by 땡보
2013. 11. 11. 01:38


최종 : 

POKO_Auto.py

#!/usr/bin/env python

#-*- coding:utf-8 -*-


import commands

import sys

import time

import os

import thread

from time import localtime, strftime

from datetime import datetime, timedelta


from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage


# global veriable definition

blockrange = [['B', [-2697555,-2169923,-5915996,-14585436,-11887922,-1641489,-13526322,-3809298,-15716030,-9192722,-15716022,-14590580,-14588532,-11360546,-14589564,-14589556,-4334618,-13532739,-14058059,-15122086,-15121053,-11296042,-14055747,-13532747,-13531459,-10245410,-13533515,-525313,-14582091,-9194794,-14057803,-5913939,-7027994,-13531715,-11888946,-14057035,-11887914,-8601882,-15713974,-15123118,-15713966,-14592653,-15117965,-15124142,-16242374,-13529395,-12413226,-13527346,-15717318,-15717054,-15717310,-15718342,-15717062,-16242630,-15718086,-10244386,-13527338,-13529394,-14054715,-13528370,-13530427,-13529403,-13003050,-13002026,-13002018,-13001002,-12937514,-12936490]],

              ['G', [-2168907,-526370,-527410,-9204216,-9205240,-7029240,-7034319,-9204208,-6507999,-1642564,-13550328,-9205232,-10256880,-3811701,-10258168,-9731568,-15130624,-9730544,-14605304,-10258160,-5914071,-10783480,-529524,-9796600,-13551352,-10850040,-4335765,-14075640,-10851056,-10259184,-10259192,-10849016,-4339110,-3811477,-7557607,-1051698,-2168907,-2167892,-4341158,-3745949,-1646716,-4338069,-14076672,-9201136,-8676848,-7033319,-8151536,-8675824,-9203184,-7558639,-12957432,-8677880,-12958464,-13548280,-8678896,-6506951,-9203192,-7031247,-13023992,-12958456,-7556600,-6503919,-13549304,-14077688,-7557599,-14077696,-4335773,-13552376,-14076664,-5979615,-3219580,-4861101,-12431096,-12432120,-12432112,-8084976,-6503920,-6504952,-8083952,-8082928,-7573026,-7559664,-7558640,-7557616,-7556592,-7032304,-7031288,-7031280,-7030264,-7030256,-6504944]],

              ['P', [-3836475,-4888131,-5413451,-1649681,-532555,-2713898,-3835443,-529442,-9220749,-6005340,-8105588,-12441278,-8698493,-12441534,-8106620,-4360771,-3241514,-1123602,-9222789,-9748109,-9222797,-2185506,-2181402,-1656090,-3832371,-2181426,-5411403,-529417,-4885059,-5937747,-4887115,-2711850,-4886091,-11915958,-11916206,-11915182,-11390638,-1126674,-1125650,-4888139,-11915950,-3307050,-530441,-11916214,-8105596,-8171133,-8172156,-8697469,-8697468,-8696444,-8696445,-8697469,-13557702,-1653010,-12442558,-13032390,-2183458,-3832114,-13557702,-4361795,-3242282,-4359483,-3307058,-3240490,-2710818,-13033414,-12966854,-12967878,-3836219,-12967870,-12966846,-3240234,-1058833,-4359739,-3242290,-3766578,-2713890,-3835451,-4887107,-4362819,-4362811,-4361787,-4360763,-4360507,-3835442,-3835186,-3834162,-3833138,-3243314,-3241258,-2715946,-2714922,-2714914]],

              ['R', [-1144180,-1671556,-1136212,-1673604,-1150597,-535635,-7210,-1671813,-542019,-3255974,-1152653,-1147269,-8637135,-1669525,-8178374,-8177351,-540995,-6012598,-6534838,-11394007,-6539966,-5416614,-2726557,-6538942,-1669492,-6537918,-1672845,-6536886,-6536894,-1676941,-2206374,-2203285,-2201237,-1073507,-544124,-2200981,-5430223,-1079676,-545108,-2200213,-2729629,-2727581,-2728605,-2725525,-3254950,-3844773,-1674885,-3845806,-3845798,-3845798,-2729638,-3845798,-1074539,-1675925,-10867407,-10868439,-1675917,-10868695,-2203293,-10869719,-11919327,-1148549,-11920351,-12443615,-12444639,-10278863,-10277839,-1080965,-1671557,-1672837,-1673613,-1672837,-1676949,-2735790,-2206373,-2205341,-2204317,-2202261,-1680029,-1680021,-1679005,-1678997,-1677973,-1674893,-1673869,-1149581,-1149573,-1147525,-1146501,-1081989]],

              ['Y', [-3830256,-12438264,-3114,-3238392,-2188784,-1057925,-11913984,-6524664,-1658303,-1651110,-535949,-6523640,-6524656,-532621,-11912952,-2190832,-6525688,-2187759,-1652191,-1124708,-2707952,-2708942,-532861,-2186727,-3238384,-2180592,-1651068,-3304944,-2180600,-5414648,-3239408,-532563,-536973,-3237360,-1657278,-2184679,-2182640,-11915000,-531581,-1129877,-10861304,-529467,-10863352,-10862328,-1127813,-1656279,-1658352,-1651934,-11913976,-12438272,-12439296,-1654255,-12439288,-12439288,-1655280,-2187760,-2186736,-2185712,-2184688,-2183664,-2181616,-1660400,-1659376,-1657328,-1656304,-1654264,-1654256,-1653232]],

              ['S', [-10276542,-6013630,-9744012,-7585470,-50862,-46749,-4364883,-45717,-44693]],

              ['F', [-15133680,-11913927,-11912903,-11386558,-14608359,-15133671,-11912902,-14607327,-11910846,-12438214,-11911870]],

              ['A', [-8625664,-10794744,-7046648,-11914992,-6521592,-7636728,-8689400,-4351480,-11914224,-4350456,-10732024,-11255544,-12965624,-12442352,-12441592,-9153024,-8105703,-5413599]]]


gamepan = [['',72,590,[1,8,7]],['',170,535,[2,8,0]],['',265,590,[3,10,9,8,1]],['',360,535,[4,10,2]],['',457,590,[5,12,11,10,3]],['',552,535,[6,12,4]],['',650,590,[13,12,5]],

           ['',72,700,[0,8,15,14]],['',170,645,[2,9,15,7,0,1]],['',265,700,[10,17,16,15,8,2]],['',360,645,[4,11,17,9,2,3]],['',457,700,[12,19,18,17,10,4]],['',552,645,[6,13,19,11,4,5]],['',650,700,[20,19,12,6]],

           ['',72,810,[7,15,22,21]],['',170,755,[9,16,22,14,7,8]],['',265,810,[17,24,23,22,15,9]],['',360,755,[11,18,24,16,9,10]],['',457,810,[19,26,25,24,17,11]],['',552,755,[13,20,26,18,11,12]],['',650,810,[27,26,19,13]],

           ['',72,920,[14,22,29,28]],['',170,865,[16,23,29,21,14,15]],['',265,920,[24,31,30,29,22,16]],['',360,865,[18,25,31,23,16,17]],['',457,920,[26,33,32,31,24,18]],['',552,865,[20,27,33,25,18,19]],['',650,920,[34,33,26,20]],

           ['',72,1030,[21,29,36,35]],['',170,975,[23,30,36,28,21,22]],['',265,1030,[31,38,37,36,29,23]],['',360,975,[25,32,38,30,23,24]],['',457,1030,[33,40,39,38,31,25]],['',552,975,[27,34,40,32,25,26]],['',650,1030,[41,40,33,27]],

           ['',72,1140,[28,36]],['',170,1085,[35,28,29,30,37]],['',265,1140,[36,30,38]],['',360,1085,[37,30,31,32,39]],['',457,1140,[38,32,40]],['',552,1085,[39,32,33,34,41]],['',650,1140,[40,34]]]


try:

    # connection to the current device, and return a MonkeyDevice object

    print "Please connect your device to your PC!!"

    device = MonkeyRunner.waitForConnection()


    def ChkAppState():

        AppInstall = device.shell('pm path com.nhncorp.SKPOCO')

        if AppInstall.startswith('package:'):

            print "POKOPANG is already installed."

        else:

            print "You should have install POKOPANG from google play."

            print "Process will be terminated."

            sys.exit(0)


        ChkAppLaunched = device.shell('ps')


        if ChkAppLaunched.find('com.nhncorp.SKPOCO'):

            print "POKOPANG is already launched!!"

            print "Kill exist process of POKOPANG!!"

            device.shell("am force-stop com.nhncorp.SKPOCO")

            MonkeyRunner.sleep(2)


        print "Launching POKOPANG..."

        device.startActivity(component='com.nhncorp.SKPOCO/com.treenod.android.UnityPlayerActivity')

        # Launching Pokopang.. in my device!!

        # device.touch(270, 600, MonkeyDevice.DOWN_AND_UP)

        # MonkeyRunner.sleep(1)

        # device.touch(440, 780, MonkeyDevice.DOWN_AND_UP)

        # MonkeyRunner.sleep(20)


    def TSS():

        try:

            while True:

                os.system('adb shell /system/bin/screencap -p /sdcard/tempscshot.png')

                os.system('adb pull /sdcard/tempscshot.png tempscshot.png')

                #ResultImage = device.takeSnapshot()

                ResultImage = MonkeyRunner.loadImageFromFile("tempscshot.png")

                if ResultImage:

                    return ResultImage

                    break

                else:

                    pass

        except Exception, e:

            print e.message, e.duration

            print "Error occur in takeSnapshot"

            sys.exit(-1)


    def IsNumber(s):

        try:

            float(s)

            return True

        except ValueError:

            return False


    def RtAddTime(sec):

        tempdt = datetime.now() + timedelta(seconds=sec)

        return tempdt.strftime("%Y%m%d.%H%M%S")


    def GetTimeFromNTP(ntpserver):

        nowtime = device.shell('rdate -sp ' + ntpserver)

        date_object = datetime.strptime(str(nowtime), "%a %b %d %I:%M:%S %Y")

        date_object = date_object + timedelta(seconds=32400)

        return date_object.strftime("%Y%m%d.%H%M%S")


    def SetDeviceTime(dtstr):

        f = open('tempdate.dat', 'w')

        f.write(dtstr)

        f.close()

        os.system('adb push tempdate.dat /sdcard/tempdate.dat')

        retval = device.shell("su -c 'sh ./sdcard/myshell.sh'")

        print str(retval)

        print "SetDeviceTime to " + str(dtstr)


    def ReChargeClover():

        # 277,237 ==> -7021766(Green clover) -9222896(No clover)

        cnt = 1

        while True:

            if TSS().getRawPixelInt(277, 237) == -7021766:

                print "Recharging complete!!"

                break

            print "Now Time : " + datetime.now().strftime("%Y%m%d.%H%M%S")

            SetDeviceTime(RtAddTime(360*cnt))

            print "After add(360sec) time : " + datetime.now().strftime("%Y%m%d.%H%M%S")

            cnt += 1

            MonkeyRunner.sleep(1)


    def ChkCell(id, idx, bidx, dragpaths, dragedpaths):


        childcells = gamepan[idx][3]

        #print "ID[" + str(idx) + "] childcell : " +  str(childcells)


        dragpaths[id].append(idx)


        for childcell in childcells:

            if childcell in dragpaths[id]:

                continue

            if gamepan[idx][0] == gamepan[childcell][0]:

                ChkCell(id, childcell, idx, dragpaths, dragedpaths)

                if id == idx:

                    if len(dragpaths[id]) >= 3:

                        dragedpaths.append(dragpaths[id])

                        dragpaths[id] = []

                        dragpaths[id].append(idx)

                    else:

                        dragpaths[id] = []

                        dragpaths[id].append(idx)


    def PlayGame():

        

        while True:

            print "Rescan!!"

            RstImg = TSS()

            dragpaths = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]

            dragedpaths = []

            sumofelement = []


            for idx in range(0,len(gamepan)):

                gamepan[idx][0] = RstImg.getRawPixelInt(gamepan[idx][1], gamepan[idx][2])

                #print "IDX[" + str(idx) + "]:" + str(gamepan[idx][0])


            #print gamepan

            for idx in range(0,len(gamepan)):

                for idx2 in range(0,len(blockrange)):

                    if gamepan[idx][0] in blockrange[idx2][1]:

                        gamepan[idx][0] = blockrange[idx2][0]


            notfoundcnt = 0

            for idx in range(0,len(gamepan)):

                if IsNumber(gamepan[idx][0]):

                    print "IDX[" + str(idx) + "]:" + str(gamepan[idx][0])

                    #RstImg.getSubImage((gamepan[idx][1]-30,gamepan[idx][2]-30,60,60)).writeToFile(strftime("%Y%M%d_%H%M", localtime()) + "_" + str(idx) + str(gamepan[idx][0]) + ".png")

                    notfoundcnt += 1

            #print gamepan


            if notfoundcnt >= 35:

                print "Not recognized more then 35 blocks!! maybe the game is over!!"

                break


            for idx in range(0, len(gamepan)):

                thread.start_new_thread(ChkCell,(idx, idx, -1, dragpaths, dragedpaths))


            #print "dragedpaths : " + str(dragedpaths)

            

            for idx in range(0, len(dragedpaths)):

                if sum(dragedpaths[idx]) in sumofelement:

                    print "maybe this element(" + str(dragedpaths[idx]) + ") is already dragged so we will skip it!!"

                    continue

                else:

                    sumofelement.append(sum(dragedpaths[idx]))

                    

                device.touch(gamepan[dragedpaths[idx][0]][1], gamepan[dragedpaths[idx][0]][2], MonkeyDevice.DOWN)

                MonkeyRunner.sleep(0.04)

                print "\nDrag Path : ",

                for node in dragedpaths[idx]:

                    print str(node),

                    device.touch(gamepan[node][1], gamepan[node][2], MonkeyDevice.MOVE)

                    MonkeyRunner.sleep(0.04)

                device.touch(gamepan[node][1], gamepan[node][2], MonkeyDevice.UP)

                MonkeyRunner.sleep(0.04)

                print " "


            for idx in range(0, len(gamepan)):

                device.touch(gamepan[idx][1], gamepan[idx][2], MonkeyDevice.DOWN_AND_UP)

                MonkeyRunner.sleep(0.03)


    def main():

        # starting script

        print "POKOPANG starting..."


        """

        device.touch(185, 1075, MonkeyDevice.DOWN_AND_UP)

        MonkeyRunner.sleep(1)

        """

        """

        print TSS().getRawPixelInt(660, 420)

        print device.takeSnapshot().getRawPixelInt(355, 1240)

        sys.exit(0)

        """

        

        # Check the state of POKOPANG

        ChkAppState()


        chk_time = 0

        while True:

            if TSS().getRawPixelInt(60, 240) == -4892416:

                print "Launching is complete!!"

                MonkeyRunner.sleep(1)

                skipnotice = False

                break

            else:

                print "Waiting for Launch..."

                MonkeyRunner.sleep(1)

                if TSS().getRawPixelInt(60, 240) == -4327573:

                    chk_time = chk_time + 1

                    if chk_time >= 3:

                        skipnotice = True

                        break


        if skipnotice == False:

            # Check Notice popup and close it!!

            print "Check daily notice!! and close it all!"

            while True:

                if TSS().getRawPixelInt(60, 240) == -4892416:

                    # Notice

                    # -4892416

                    # 600, 250

                    device.touch(600, 250, MonkeyDevice.DOWN_AND_UP)

                    MonkeyRunner.sleep(1)

                    Chk_Time = 0

                else:

                    if Chk_Time <= 3:

                        Chk_Time = Chk_Time + 1

                        MonkeyRunner.sleep(0.5)

                    else:

                        #MonkeyRunner.sleep(1)

                        break


        # Start of main cycle

        while True:

            print "Start of main cycle!!"

            while True:

                TSS_IMG = TSS()

                #getRawPixelInt(277, 237) == -10592064:

                #if TSS_IMG.getRawPixelInt(60, 240) == -4327573 and TSS_IMG.getRawPixelInt(670, 1130) == -4892416:

                if TSS_IMG.getRawPixelInt(277, 237) == -7021766 and TSS_IMG.getRawPixelInt(670, 1130) == -4892416:

                    print "It is ok to play game!!"

                    # To go to play game

                    # 350, 1070

                    break

                else:

                    device.touch(355, 1240, MonkeyDevice.DOWN_AND_UP)

                    print "Wait a moment and Rechanging clover!!"

                    if TSS_IMG.getRawPixelInt(670, 1130) == -4892416:

                        ReChargeClover()

                        SetDeviceTime(GetTimeFromNTP('time.bora.net'))

                    # Wait For time

                    MonkeyRunner.sleep(10)


            device.touch(350, 1070, MonkeyDevice.DOWN_AND_UP)

            MonkeyRunner.sleep(1)

            device.touch(350, 1070, MonkeyDevice.DOWN_AND_UP)

            MonkeyRunner.sleep(2)


            Chk_Time = 0

            while True:

                if TSS().getRawPixelInt(660, 420) == -4892416:

                    print "Help notice is showed!!"

                    device.touch(195, 960, MonkeyDevice.DOWN_AND_UP)

                    MonkeyRunner.sleep(1)

                else:

                    if Chk_Time <= 3:

                        Chk_Time = Chk_Time + 1

                        MonkeyRunner.sleep(0.5)

                    else:

                        break


            # -56246

            while True:

                #if TSS().getRawPixelInt(30, 45) == -56246:

                #if TSS().getRawPixelInt(660, 420) != -4892416:

                #if TSS().getRawPixelInt(678, 1100) not in (-16777024, -4892416, -7590623, -16736410):

                if TSS().getRawPixelInt(27, 1144) not in (-9225984, -7058168, -15135744, -7584504, -7585536, -14609400, -4360919, -14083056):

                    print "Game is playing!!"

                    PlayGame()

                    MonkeyRunner.sleep(1)

                else:

                    print "Game over!!"

                    Chk_Time = 0

                    while True:

                        if TSS().getRawPixelInt(27, 1144) != -9225984:

                            if TSS().getRawPixelInt(27, 1144) == -14609400:

                                print "Close monster info!"

                                device.touch(350, 880, MonkeyDevice.DOWN_AND_UP)

                                MonkeyRunner.sleep(1)

                            if TSS().getRawPixelInt(27, 1144) == -7058168:

                                print "Close monster list!"

                                device.touch(630, 230, MonkeyDevice.DOWN_AND_UP)

                                MonkeyRunner.sleep(1)

                            if TSS().getRawPixelInt(27, 1144) == -15135744:

                                print "Close mission info!"

                                device.touch(360, 800, MonkeyDevice.DOWN_AND_UP)

                                MonkeyRunner.sleep(1)

                            if TSS().getRawPixelInt(27, 1144) == -7584504:

                                if TSS().getRawPixelInt(150, 630) == -3240407:

                                    print "Close item store!"

                                    device.touch(630, 330, MonkeyDevice.DOWN_AND_UP)

                                    MonkeyRunner.sleep(1)

                            if TSS().getRawPixelInt(27, 1144) == -7585536:

                                print "Close upgrade shop!"

                                device.touch(630, 330, MonkeyDevice.DOWN_AND_UP)

                                MonkeyRunner.sleep(1)

                            if TSS().getRawPixelInt(27, 1144) == -14083056:

                                if TSS().getRawPixelInt(150, 630) == -10249728:

                                    print "Close send clover info!"

                                    device.touch(360, 800, MonkeyDevice.DOWN_AND_UP)

                                    MonkeyRunner.sleep(1)

                                if TSS().getRawPixelInt(150, 630) == -10249728:

                                    print "Close send clover info!"

                                    device.touch(360, 800, MonkeyDevice.DOWN_AND_UP)

                                    MonkeyRunner.sleep(1)

                                if TSS().getRawPixelInt(150, 630) == -14053715:

                                    print "Close today mission window!"

                                    device.touch(360, 800, MonkeyDevice.DOWN_AND_UP)

                                    MonkeyRunner.sleep(1)

                                if TSS().getRawPixelInt(150, 630) == -7060224:

                                    print "Close profile!"

                                    device.touch(355, 915, MonkeyDevice.DOWN_AND_UP)

                                    MonkeyRunner.sleep(1)

                            if TSS().getRawPixelInt(27, 1144) == -4360919:

                                break

                        else:

                            if Chk_Time <= 3:

                                Chk_Time = Chk_Time + 1

                                MonkeyRunner.sleep(0.5)

                            else:

                                break

                    MonkeyRunner.sleep(1)

                    break


            # 40, 945 ==> -10859455 ==> 645, 970

            while TSS().getRawPixelInt(660, 420) == -4892416:

                # Add Time Notice or High score notice!!

                device.touch(195, 960, MonkeyDevice.DOWN_AND_UP)

                MonkeyRunner.sleep(1)

                

                while True:

                    if TSS().getRawPixelInt(40, 945) == -10859455:

                        print "Notice pop up!!"

                        device.touch(665, 947, MonkeyDevice.DOWN_AND_UP)

                        MonkeyRunner.sleep(1)

                    else:

                        print "Notice is not exists!!"

                        break


                # 40, 945 ==> -4892416 ==> 185, 1075

                while True:

                    if TSS().getRawPixelInt(40, 945) == -4892416:

                        print "Game score pop up!!"

                        device.touch(185, 1075, MonkeyDevice.DOWN_AND_UP)

                        MonkeyRunner.sleep(1)

                    else:

                        print "Game score popup is closed!!"

                        MonkeyRunner.sleep(1)

                        break


            print "End of main cycle.."

            print "Restarting..."



    if __name__ == "__main__":

        main()

finally:

    device.shell("am force-stop com.android.commands.monkey")




2013-11-13


jython_test0001.py


jython_test0002.py


POKO_Auto.py


POKO_Auto_Fin.py


test001.py

포코팡오토_색상변위표.xlsx


older_version

POKO_Auto.py


'Study > python' 카테고리의 다른 글

[펌]Python code coverage for Lib/ctypes/wintypes.py  (0) 2014.10.12
shutil copyfileobj ()  (0) 2014.09.03
[펌]python thread 사용예  (0) 2013.10.16
[연습]wxpython rss reader  (0) 2013.10.06
wxpython webview test  (0) 2013.10.05
Posted by 땡보
2013. 11. 5. 09:15
Posted by 땡보
2013. 10. 16. 14:23



참고: http://docs.python.org/library/thread.html



1. 가장 기초적인 Thread

thread.start_new_thread(func, args, kwargs=None)
  func = thread 실행 함수
  args = func에 넘겨줄 인수
  kwargs = 키워드 인수

#!/usr/bin/python 
import thread, time

# thread에서 실행될 함수
def counter(id): 
    for in range(5):
        print 'id %s --> %s' % (id, i)
        time.sleep(0.1)

# thread 5개 실행
for 
in range(5):
    thread.start_new_thread(counter, (i,))

# thread가 다 돌 때까지 대기
time.sleep(1)
print 'Exiting'






2. Critical Section

thread.allocate_lock() : critical section에 사용할 lock 객체 리턴
lock.acquire() : lock을 건다
lock.release() : 걸었던 lock 해제
lock.locked() : lock이 걸려있는지 검사. 락이 걸려 있으면 True, 아니면 False

#!/usr/bin/python 
import thread, time

g_count = 0
# lock 객체 생성
lock = thread.allocate_lock()

def counter(id, count):
    global g_count
    for in range(count):
        print 'id %s --> %s' % (id, i)
        # lock 건다
        lock.acquire()
        # 전역변수 핸들링
        g_count = g_count + 1
        # lock 해제
        lock.release()

for in range(5):
    thread.start_new_thread(counter, (i, 5))

time.sleep(1)
print 'Total Count = ', g_count
print 'Exiting'







3. thread 종료 대기

#!/usr/bin/python
import thread, time

# 생성할 Thread 갯수 지정
NumberOfThread = 5
# 실행중인 Thread 갯수
ThreadsLeft = NumberOfThread

# Critical Section에 사용할 lock 객체 생성
lock = thread.allocate_lock()

# Thread 종료처리 함수
def threadexit(id):
    global ThreadsLeft
    print 'thread %d is quitting' % id
    lock.acquire()
    ThreadsLeft -= 1
    lock.release()


def counter(id, count):
    for in range(count):
        print 'id %s --> %s' % (id, i)
    threadexit(id) # thread 종료처리 함수 호출

# NumberOfThread 만큼 Thread 생성

for in range(NumberOfThread):
    thread.start_new_thread(counter, (i, 5))

# 모든 Thread가 종료될 때 까지 대기
while ThreadsLeft:
    time.sleep(0.1)

print 'Exiting'


thread 보다 객체지향적인 방법으로 사용가능한 thread 객체.
Delphi의 TThread와 유사한 형태.



1. 생성자에 직접 함수 전달

#!/usr/bin/python

import threading, time

def myThread(id):
    for in range(10):
        print 'id=%s --> %s' % (id, i)
        # CPU 양보
        time.sleep(0)

# thread 객체를 모아둘 리스트
threads = []

for in range(2):
    # myThread를 실행하는 thread 생성
    th = threading.Thread(target=myThread, args=(i,))
    # thread 시작
    th.start()
    # thread 객체리스트에 추가
    threads.append(th)

# thread 종료까지 대기
for th in threads:
    th.join()

print 'Exiting'







2. 서브클래스에서 run method 재정의
  (delphi의 TThread 클래스에서 Execute를 override해서 사용하는 방법과 유사함)

#!/usr/bin/python

import threading, time

# threading 상속
class MyThread(threading.Thread):
    # thread 실행본체인 run method 재정의
    def run(self):
        for in range(10):
            print 'id=%s --> %s' % (self.getName(), i) # self.getName은 Thread 이름 반환
            time.sleep(0)


threads = []

for in range(2):
    th = MyThread()
    th.start()
    threads.append(th)


for th in threads:
    th.join()

print 'Exiting'







3. Critical Section

#!/usr/bin/python 

import threading, time

# 전역변수
g_count = 0

class MyThread(threading.Thread)
    def run(self):
        global g_count
        for in range(10):
            # lock
            lock.acquire()
            # 전역변수 핸들링
            g_count += 1
            # 실제로 2개 이상의 Thread가 동시에 전역변수를 핸들링하도록 sleep
            time.sleep(0.1)
            # 어느 thread 가 전역변수를 어떻게 바꿨는지 print
            print '[%s] g_count = %s' % (self.getName(), g_count)
            # lock 해제
            lock.release()


# Lock 객체 생성
lock = threading.Lock()

threads = []

for in range(2):
    th = MyThread()
    th.start()
    threads.append(th)

for th in threads:
    th.join()

print 'TotalCount = ', g_count
print 'Exiting'





'Study > python' 카테고리의 다른 글

shutil copyfileobj ()  (0) 2014.09.03
[연습]AutoPOKO ~~  (0) 2013.11.11
[연습]wxpython rss reader  (0) 2013.10.06
wxpython webview test  (0) 2013.10.05
[연습중]MK RSS 파싱  (0) 2013.09.23
Posted by 땡보
2013. 10. 6. 16:01




setup.exe


wx_browsertest.py


2013.10.18 - final

#!/usr/bin/env python

#-*- coding:utf-8 -*-


from bs4 import BeautifulSoup

import wx

import wx.html2

import urllib2

import re

import thread

import time


news_url = u""


#----------------------------------------------------------------------

class ReaderPanel(wx.Panel):


    def __init__(self, parent):


        wx.Panel.__init__(self, parent)


        self.current = news_hosts[8]

        self.frame = self.GetTopLevelParent()

        self.titleBase = self.frame.GetTitle()


        sizer = wx.BoxSizer(wx.VERTICAL)

        

        grpSizer = wx.BoxSizer(wx.HORIZONTAL)

        

        st1 = wx.StaticText(self, label=u"뉴스카테고리 : ")

        grpSizer.Add(st1, 0, wx.CENTER|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"새로고침", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnReload, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"헤드라인", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo0, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"전체뉴스", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo1, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"경제", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo2, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"정치", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo3, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"사회", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo4, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"국제", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo5, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"기업경영", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo6, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"증권", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo7, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"부동산", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo8, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"문화연예", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo9, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"패션", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo10, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"스포츠", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo11, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"게임", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo12, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"오피니언", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo13, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        sizer.Add(grpSizer, 0, wx.EXPAND)

        

        sizer.Add((-1, 10))

        

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)


        #btn = wx.Button(self, -1, u"Open", style=wx.BU_EXACTFIT)

        #self.Bind(wx.EVT_BUTTON, self.OnOpenButton, btn)

        #btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        #btn = wx.Button(self, -1, u"<--", style=wx.BU_EXACTFIT)

        #self.Bind(wx.EVT_BUTTON, self.OnPrevPageButton, btn)

        #btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        #self.Bind(wx.EVT_UPDATE_UI, self.OnCheckCanGoBack, btn)


        #btn = wx.Button(self, -1, u"-->", style=wx.BU_EXACTFIT)

        #self.Bind(wx.EVT_BUTTON, self.OnNextPageButton, btn)

        #btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        #self.Bind(wx.EVT_UPDATE_UI, self.OnCheckCanGoForward, btn)


        #btn = wx.Button(self, -1, u"Stop", style=wx.BU_EXACTFIT)

        #self.Bind(wx.EVT_BUTTON, self.OnStopButton, btn)

        #btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        #btn = wx.Button(self, -1, u"Refresh", style=wx.BU_EXACTFIT)

        #self.Bind(wx.EVT_BUTTON, self.OnRefreshPageButton, btn)

        #btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        txt = wx.StaticText(self, -1, u"Location:")

        btnSizer.Add(txt, 0, wx.CENTER|wx.ALL, 2)


        self.location = wx.ComboBox(

            self, -1, "", style=wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER)

        self.location.AppendItems([u"http://www.mk.co.kr/"])


        self.Bind(wx.EVT_COMBOBOX, self.OnLocationSelect, self.location)

        self.location.Bind(wx.EVT_TEXT_ENTER, self.OnLocationEnter)

        btnSizer.Add(self.location, 1, wx.EXPAND|wx.ALL, 2)


        sizer.Add(btnSizer, 0, wx.EXPAND)

        

        sizer.Add((-1, 10))

        

        self.wv = wx.html2.WebView.New(self)

        self.Bind(wx.html2.EVT_WEBVIEW_NAVIGATING, self.OnWebViewNavigating, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_NAVIGATED, self.OnWebViewNavigated, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_LOADED, self.OnWebViewLoaded, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_TITLE_CHANGED, self.OnWebViewTitleChanged, self.wv)

        sizer.Add(self.wv, 1, wx.EXPAND)

        

        self.SetSizer(sizer)


        #self.wv.LoadURL(self.current)

        self.wv.SetPage(news_rss[8], news_hosts[8])

        


    # WebView events

    def OnWebViewNavigating(self, evt):

        # this event happens prior to trying to get a resource

        print u"OnWebViewNavigating URL is : %s" % evt.GetURL()

        #wx.MessageBox(evt.GetURL(), u"Target URL is...", wx.OK|wx.ICON_INFORMATION, self)

        # 1. URL이 기사 URL타입과 일치하면... 파싱 아니면 그냥 웹표시

        if (u"http://mk.co.kr.feedsportal.com/c/" in evt.GetURL()) and (not u"/index.rss" in evt.GetURL()):

            news_url = evt.GetURL()

            news_script = SetPage(evt.GetURL(), u"MK")

            self.wv.SetPage(u"<html><div>" + news_script + u"</div></html>", news_url)

            evt.Veto()

            self.current = news_url

            self.location.SetString(0, self.current)

        elif (u"http://mk.co.kr.feedsportal.com/c/" in evt.GetURL()) and (u"/index.rss" in evt.GetURL()):

            news_url = evt.GetURL()

            news_script = SetPage(evt.GetURL(), u"TITLE")

            self.wv.SetPage(news_script, news_url)

            evt.Veto()

            self.current = news_url

            self.location.SetString(0, self.current)



    def OnWebViewNavigated(self, evt):

        self.frame.SetStatusText(u"Loading %s..." % evt.GetURL())


    def OnTestButton(self, evt):

        pass


    def OnWebViewLoaded(self, evt):

        # The full document has loaded

        self.current = evt.GetURL()

        if self.current == u"http:///":

            self.current = self.location.GetString(0)

            self.location.SetValue(self.location.GetString(0))

        else:

            self.location.SetValue(self.current)

        self.frame.SetStatusText(u"Loaded")

        #self.wv.RunScript("""alert('""" + self.current + """');""")

        #self.wv.RunScript("""

        #//call logIn();

        #//document.getElementsByName('q')[0].value="hist";

        #//document.getElementById('openididentifier').value="ident";

        #""")

        #self.wv.SetPage(self, """<html>하하하</html>""", """http://www.naver.com""")



    def OnWebViewTitleChanged(self, evt):

        # Set the frame's title to include the document's title

        self.frame.SetTitle("%s -- %s" % (self.titleBase, evt.GetString()))


    # Control bar events

    def OnLocationSelect(self, evt):

        url = self.location.GetStringSelection()

        print(u"OnLocationSelect: %s\n" % url)

        self.wv.LoadURL(url)


    def OnLocationEnter(self, evt):

        url = self.location.GetValue()

        self.location.Append(url)

        self.wv.LoadURL(url)


    def OnOpenButton(self, event):

        dlg = wx.TextEntryDialog(self, u"Input Url or local file path", u"URL", self.current, wx.OK|wx.CANCEL)

        dlg.CentreOnParent()


        if dlg.ShowModal() == wx.ID_OK:

            self.current = dlg.GetValue()

            self.wv.LoadURL(self.current)


        dlg.Destroy()


    def OnPrevPageButton(self, event):

        for i in self.wv.GetBackwardHistory():

            print i.Url, i.Title

        self.wv.GoBack()

        #self.wv.LoadURL(u"http://mk.co.kr.feedsportal.com/c/34147/f/618380/index.rss")


    def OnNextPageButton(self, event):

        for i in self.wv.GetForwardHistory():

            print i.URL, i.Title

        self.wv.GoForward()


    def OnCheckCanGoBack(self, event):

        event.Enable(self.wv.CanGoBack())


    def OnCheckCanGoForward(self, event):

        event.Enable(self.wv.CanGoForward())


    def OnStopButton(self, evt):

        self.wv.Stop()


    def OnRefreshPageButton(self, evt):

        self.wv.Reload()


    def OnReload(self, evt):

        grap_news_title()

        self.current = news_hosts[8]

        self.wv.SetPage(news_rss[8], self.current)

        

    def OnGoTo0(self, evt):

        self.current = news_hosts[0]

        self.wv.SetPage(news_rss[0], self.current)

    

    def OnGoTo1(self, evt):

        self.current = news_hosts[1]

        self.wv.SetPage(news_rss[1], self.current)


    def OnGoTo2(self, evt):

        self.current = news_hosts[2]

        self.wv.SetPage(news_rss[2], self.current)

        

    def OnGoTo3(self, evt):

        self.current = news_hosts[3]

        self.wv.SetPage(news_rss[3], self.current)

    

    def OnGoTo4(self, evt):

        self.current = news_hosts[4]

        self.wv.SetPage(news_rss[4], self.current)

        

    def OnGoTo5(self, evt):

        self.current = news_hosts[5]

        self.wv.SetPage(news_rss[5], self.current)

        

    def OnGoTo6(self, evt):

        self.current = news_hosts[6]

        self.wv.SetPage(news_rss[6], self.current)

        

    def OnGoTo7(self, evt):

        self.current = news_hosts[7]

        self.wv.SetPage(news_rss[7], self.current)

        

    def OnGoTo8(self, evt):

        self.current = news_hosts[8]

        self.wv.SetPage(news_rss[8], self.current)

        

    def OnGoTo9(self, evt):

        self.current = news_hosts[9]

        self.wv.SetPage(news_rss[9], self.current)

        

    def OnGoTo10(self, evt):

        self.current = news_hosts[10]

        self.wv.SetPage(news_rss[10], self.current)

        

    def OnGoTo11(self, evt):

        self.current = news_hosts[11]

        self.wv.SetPage(news_rss[11], self.current)

        

    def OnGoTo12(self, evt):

        self.current = news_hosts[12]

        self.wv.SetPage(news_rss[12], self.current)

        

    def OnGoTo13(self, evt):

        self.current = news_hosts[13]

        self.wv.SetPage(news_rss[13], self.current)


#----------------------------------------------------------------------

def GetUrlSrc(as_url, as_decoding):

    html_src = urllib2.urlopen(as_url).read()

    return html_src.decode(as_decoding, 'ignore')


def SetPage(as_url, as_site, return_val=None, return_idx=None):

    ls_temp_header = u"""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

                        <html xmlns="http://www.w3.org/1999/xhtml">

                        <head>

                        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

                        <style type="text/css">

                        body {

                            margin-left: 10px;

                            margin-top: 10px;

                            margin-right: 10px;

                            margin-bottom: 10px;

                        }

                        .news {

                            font-family: "돋움체";

                            font-size: 14px;

                        }

                        </style>

                        </head>

                        

                        <body>"""

                        

    ls_temp_footer = u"""</body></html>"""

    

    # 1. URL이 기사 URL타입과 일치하면... 파싱 아니면 그냥 웹표시

    if as_site == u"MK":

        title_pattern = "<title>(.*?)</title>".decode("utf-8", "ignore")

        script_pattern = "<div\sclass=\'read_txt\'>(.*?)\s*?<!--이미지".decode("utf-8", "ignore")

        result_html = GetUrlSrc(as_url, u"cp949")

        #wx.MessageBox(result_html, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        result_text = re.findall(script_pattern, result_html, re.DOTALL)

        result_title = re.findall(title_pattern, result_html, re.DOTALL)

        print result_title

        if result_text:

            #wx.MessageBox(result_text[0], u"Test", wx.OK|wx.ICON_INFORMATION, self)

            #ls_return = " ".join(str(re.sub("<[^>]*>".decode("utf-8", "ignore"), "".decode("utf-8", "ignore"), result_text[0]).encode("cp949", "ignore")).split())

            #wx.MessageBox(result_text[0], u"News", wx.OK|wx.ICON_INFORMATION)

            return ls_temp_header + u"""<title>""" + result_title[0] + u"""</title>""" + result_text[0] + ls_temp_footer

    elif as_site == u"TITLE":

        html_src_uni = GetUrlSrc(as_url, 'utf-8')

        soup = BeautifulSoup(html_src_uni)

        ls_temp = str(soup('title')).decode('utf-8', 'ignore')

        pattern = u'<title>(.*?)</title>'

        ls_result_title = re.findall(pattern, ls_temp, re.DOTALL)

        ls_temp = str(soup('link')).decode('utf-8', 'ignore')

        pattern = u'<link>(.*?)</link>'

        ls_result_link = re.findall(pattern, ls_temp, re.DOTALL)

        ls_temp = str(soup('description')).decode('utf-8', 'ignore')

        ls_temp = ls_temp.replace(u'신문기사</description>', u'신문기사..&lt;img')

        pattern = u'<description>(.*?)..&lt;img'

        ls_result_description = re.findall(pattern, ls_temp, re.DOTALL)

        

        ls_temp_body_header = u"""<title>""" + ls_result_title[0] + u"""</title>""" + u"""<table width="1010" height="25" border="0" cellpadding="0" cellspacing="0"><tr><td width="1000" height="10" class="news">"""

        ls_temp_body_footer = u"""</a></td></tr></table>"""

        ls_temp_body = u""

        for ll_idx in range(len(ls_result_title)):

            if ll_idx == 0:

                continue

            ls_temp_body = ls_temp_body + ls_temp_body_header + str(ll_idx) + u" : " + u"""<a href=" """ + ls_result_link[ll_idx] + u""" ">""" + ls_result_title[ll_idx] + ls_temp_body_footer

        

        if return_val == None:

            return ls_temp_header + ls_temp_body + ls_temp_footer

        else:

            return_val[return_idx] = ls_temp_header + ls_temp_body + ls_temp_footer

            threadexit()


def threadexit():

    global threadsleft

    lock.acquire()

    threadsleft -= 1

    lock.release()


def grap_news_title():

    global threadsleft 

    

    threadsleft = len(news_hosts)

    print len(news_hosts)

    

    for i in range(len(news_hosts)):

        news_rss.append(u"")

        thread.start_new_thread(SetPage, (news_hosts[i], u"TITLE", news_rss, i ))

        

    while threadsleft:

        pass


def main():

    

    global news_rss, threadsleft, lock, news_hosts

    news_rss = [u""]

    lock = thread.allocate_lock()


    news_hosts = [u"http://mk.co.kr.feedsportal.com/c/34147/f/618372/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618373/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618374/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618375/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618376/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618377/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618378/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618379/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618380/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618381/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/651700/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/651701/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618383/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618384/index.rss"]


    start = time.time()

    

    grap_news_title()


    print time.time() - start

    

    app = wx.App()

    frm = wx.Frame(None, style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER | wx.FRAME_EX_METAL, title=u"MK_RSS Reader v0.9", size=(1048,768))

    frm.CreateStatusBar()

    ico = wx.Icon(u"MK_RSS.ico", wx.BITMAP_TYPE_ICO)

    frm.SetIcon(ico)

    pnl = ReaderPanel(frm)

    frm.Show()

    frm.Center()

    app.MainLoop()


#----------------------------------------------------------------------

if __name__ == '__main__':

    main()

2013.10.15

#!/usr/bin/env python

#-*- coding:utf-8 -*-


from bs4 import BeautifulSoup

import wx

import wx.html2

import urllib2

import re

import thread

import time


news_url = u""


#----------------------------------------------------------------------

class TestPanel(wx.Panel):


    def __init__(self, parent):


        wx.Panel.__init__(self, parent)


        self.current = news_hosts[8]

        self.frame = self.GetTopLevelParent()

        self.titleBase = self.frame.GetTitle()


        sizer = wx.BoxSizer(wx.VERTICAL)

        

        grpSizer = wx.BoxSizer(wx.HORIZONTAL)

        

        st1 = wx.StaticText(self, label='News Category : ')

        grpSizer.Add(st1, 0, wx.CENTER|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"헤드라인", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo0, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"전체뉴스", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo1, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"경제", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo2, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"정치", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo3, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"사회", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo4, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"국제", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo5, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"기업경영", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo6, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"증권", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo7, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"부동산", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo8, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"문화연예", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo9, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"패션", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo10, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"스포츠", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo11, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"게임", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo12, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"오피니언", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoTo13, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        sizer.Add(grpSizer, 0, wx.EXPAND)

        

        sizer.Add((-1, 10))

        

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)


        #btn = wx.Button(self, -1, u"Open", style=wx.BU_EXACTFIT)

        #self.Bind(wx.EVT_BUTTON, self.OnOpenButton, btn)

        #btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        #btn = wx.Button(self, -1, u"<--", style=wx.BU_EXACTFIT)

        #self.Bind(wx.EVT_BUTTON, self.OnPrevPageButton, btn)

        #btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        #self.Bind(wx.EVT_UPDATE_UI, self.OnCheckCanGoBack, btn)


        #btn = wx.Button(self, -1, u"-->", style=wx.BU_EXACTFIT)

        #self.Bind(wx.EVT_BUTTON, self.OnNextPageButton, btn)

        #btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        #self.Bind(wx.EVT_UPDATE_UI, self.OnCheckCanGoForward, btn)


        #btn = wx.Button(self, -1, u"Stop", style=wx.BU_EXACTFIT)

        #self.Bind(wx.EVT_BUTTON, self.OnStopButton, btn)

        #btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        #btn = wx.Button(self, -1, u"Refresh", style=wx.BU_EXACTFIT)

        #self.Bind(wx.EVT_BUTTON, self.OnRefreshPageButton, btn)

        #btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        txt = wx.StaticText(self, -1, u"Location:")

        btnSizer.Add(txt, 0, wx.CENTER|wx.ALL, 2)


        self.location = wx.ComboBox(

            self, -1, "", style=wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER)

        self.location.AppendItems([u"http://www.mk.co.kr/"])


        self.Bind(wx.EVT_COMBOBOX, self.OnLocationSelect, self.location)

        self.location.Bind(wx.EVT_TEXT_ENTER, self.OnLocationEnter)

        btnSizer.Add(self.location, 1, wx.EXPAND|wx.ALL, 2)


        sizer.Add(btnSizer, 0, wx.EXPAND)

        

        sizer.Add((-1, 10))

        

        self.wv = wx.html2.WebView.New(self)

        self.Bind(wx.html2.EVT_WEBVIEW_NAVIGATING, self.OnWebViewNavigating, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_NAVIGATED, self.OnWebViewNavigated, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_LOADED, self.OnWebViewLoaded, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_TITLE_CHANGED, self.OnWebViewTitleChanged, self.wv)

        sizer.Add(self.wv, 1, wx.EXPAND)

        

        self.SetSizer(sizer)


        #self.wv.LoadURL(self.current)

        self.wv.SetPage(news_rss[8], news_hosts[8])

        


    # WebView events

    def OnWebViewNavigating(self, evt):

        # this event happens prior to trying to get a resource

        print u"OnWebViewNavigating URL is : %s" % evt.GetURL()

        #wx.MessageBox(evt.GetURL(), u"Target URL is...", wx.OK|wx.ICON_INFORMATION, self)

        # 1. URL이 기사 URL타입과 일치하면... 파싱 아니면 그냥 웹표시

        if (u"http://mk.co.kr.feedsportal.com/c/" in evt.GetURL()) and (not u"/index.rss" in evt.GetURL()):

            news_url = evt.GetURL()

            news_script = SetPage(evt.GetURL(), u"MK")

            self.wv.SetPage(u"<html><div>" + news_script + u"</div></html>", news_url)

            evt.Veto()

            self.current = news_url

            self.location.SetString(0, self.current)

        elif (u"http://mk.co.kr.feedsportal.com/c/" in evt.GetURL()) and (u"/index.rss" in evt.GetURL()):

            news_url = evt.GetURL()

            news_script = SetPage(evt.GetURL(), u"TITLE")

            self.wv.SetPage(news_script, news_url)

            evt.Veto()

            self.current = news_url

            self.location.SetString(0, self.current)



    def OnWebViewNavigated(self, evt):

        self.frame.SetStatusText(u"Loading %s..." % evt.GetURL())


    def OnTestButton(self, evt):

        pass


    def OnWebViewLoaded(self, evt):

        # The full document has loaded

        self.current = evt.GetURL()

        if self.current == u"http:///":

            self.current = self.location.GetString(0)

            self.location.SetValue(self.location.GetString(0))

        else:

            self.location.SetValue(self.current)

        self.frame.SetStatusText(u"Loaded")

        #self.wv.RunScript("""alert('""" + self.current + """');""")

        #self.wv.RunScript("""

        #//call logIn();

        #//document.getElementsByName('q')[0].value="hist";

        #//document.getElementById('openididentifier').value="ident";

        #""")

        #self.wv.SetPage(self, """<html>하하하</html>""", """http://www.naver.com""")



    def OnWebViewTitleChanged(self, evt):

        # Set the frame's title to include the document's title

        self.frame.SetTitle("%s -- %s" % (self.titleBase, evt.GetString()))


    # Control bar events

    def OnLocationSelect(self, evt):

        url = self.location.GetStringSelection()

        print(u"OnLocationSelect: %s\n" % url)

        self.wv.LoadURL(url)


    def OnLocationEnter(self, evt):

        url = self.location.GetValue()

        self.location.Append(url)

        self.wv.LoadURL(url)


    def OnOpenButton(self, event):

        dlg = wx.TextEntryDialog(self, u"Input Url or local file path", u"URL", self.current, wx.OK|wx.CANCEL)

        dlg.CentreOnParent()


        if dlg.ShowModal() == wx.ID_OK:

            self.current = dlg.GetValue()

            self.wv.LoadURL(self.current)


        dlg.Destroy()


    def OnPrevPageButton(self, event):

        for i in self.wv.GetBackwardHistory():

            print i.Url, i.Title

        self.wv.GoBack()

        #self.wv.LoadURL(u"http://mk.co.kr.feedsportal.com/c/34147/f/618380/index.rss")


    def OnNextPageButton(self, event):

        for i in self.wv.GetForwardHistory():

            print i.URL, i.Title

        self.wv.GoForward()


    def OnCheckCanGoBack(self, event):

        event.Enable(self.wv.CanGoBack())


    def OnCheckCanGoForward(self, event):

        event.Enable(self.wv.CanGoForward())


    def OnStopButton(self, evt):

        self.wv.Stop()


    def OnRefreshPageButton(self, evt):

        self.wv.Reload()


    def OnGoTo0(self, evt):

        self.current = news_hosts[0]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[0], self.current)

    

    def OnGoTo1(self, evt):

        self.current = news_hosts[1]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[1], self.current)


    def OnGoTo2(self, evt):

        self.current = news_hosts[2]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[2], self.current)

        

    def OnGoTo3(self, evt):

        self.current = news_hosts[3]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[3], self.current)

    

    def OnGoTo4(self, evt):

        self.current = news_hosts[4]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[4], self.current)

        

    def OnGoTo5(self, evt):

        self.current = news_hosts[5]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[5], self.current)

        

    def OnGoTo6(self, evt):

        self.current = news_hosts[6]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[6], self.current)

        

    def OnGoTo7(self, evt):

        self.current = news_hosts[7]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[7], self.current)

        

    def OnGoTo8(self, evt):

        self.current = news_hosts[8]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[8], self.current)

        

    def OnGoTo9(self, evt):

        self.current = news_hosts[9]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[9], self.current)

        

    def OnGoTo10(self, evt):

        self.current = news_hosts[10]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[10], self.current)

        

    def OnGoTo11(self, evt):

        self.current = news_hosts[11]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[11], self.current)

        

    def OnGoTo12(self, evt):

        self.current = news_hosts[12]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[12], self.current)

        

    def OnGoTo13(self, evt):

        self.current = news_hosts[13]

        #self.wv.LoadURL(self.current)

        #wx.MessageBox(economy_rss, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        self.wv.SetPage(news_rss[13], self.current)


#----------------------------------------------------------------------

def GetUrlSrc(as_url, as_decoding):

    html_src = urllib2.urlopen(as_url).read()

    return html_src.decode(as_decoding, 'ignore')


def SetPage(as_url, as_site, return_val=None, return_idx=None):

    ls_temp_header = u"""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

                        <html xmlns="http://www.w3.org/1999/xhtml">

                        <head>

                        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

                        <style type="text/css">

                        body {

                            margin-left: 10px;

                            margin-top: 10px;

                            margin-right: 10px;

                            margin-bottom: 10px;

                        }

                        .news {

                            font-family: "돋움체";

                            font-size: 14px;

                        }

                        </style>

                        </head>

                        

                        <body>"""

                        

    ls_temp_footer = u"""</body></html>"""

    

    # 1. URL이 기사 URL타입과 일치하면... 파싱 아니면 그냥 웹표시

    if as_site == u"MK":

        title_pattern = "<title>(.*?)</title>".decode("utf-8", "ignore")

        script_pattern = "<div\sclass=\'read_txt\'>(.*?)\s*?<!--이미지".decode("utf-8", "ignore")

        result_html = GetUrlSrc(as_url, u"cp949")

        #wx.MessageBox(result_html, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        result_text = re.findall(script_pattern, result_html, re.DOTALL)

        result_title = re.findall(title_pattern, result_html, re.DOTALL)

        print result_title

        if result_text:

            #wx.MessageBox(result_text[0], u"Test", wx.OK|wx.ICON_INFORMATION, self)

            #ls_return = " ".join(str(re.sub("<[^>]*>".decode("utf-8", "ignore"), "".decode("utf-8", "ignore"), result_text[0]).encode("cp949", "ignore")).split())

            #wx.MessageBox(result_text[0], u"News", wx.OK|wx.ICON_INFORMATION)

            return ls_temp_header + u"""<title>""" + result_title[0] + u"""</title>""" + result_text[0] + ls_temp_footer

    elif as_site == u"TITLE":

        html_src_uni = GetUrlSrc(as_url, 'utf-8')

        soup = BeautifulSoup(html_src_uni)

        ls_temp = str(soup('title')).decode('utf-8', 'ignore')

        pattern = u'<title>(.*?)</title>'

        ls_result_title = re.findall(pattern, ls_temp, re.DOTALL)

        ls_temp = str(soup('link')).decode('utf-8', 'ignore')

        pattern = u'<link>(.*?)</link>'

        ls_result_link = re.findall(pattern, ls_temp, re.DOTALL)

        ls_temp = str(soup('description')).decode('utf-8', 'ignore')

        ls_temp = ls_temp.replace(u'신문기사</description>', u'신문기사..&lt;img')

        pattern = u'<description>(.*?)..&lt;img'

        ls_result_description = re.findall(pattern, ls_temp, re.DOTALL)

        

        ls_temp_body_header = u"""<title>""" + ls_result_title[0] + u"""</title>""" + u"""<table width="1010" height="25" border="0" cellpadding="0" cellspacing="0"><tr><td width="1000" height="10" class="news">"""

        ls_temp_body_footer = u"""</a></td></tr></table>"""

        ls_temp_body = u""

        for ll_idx in range(len(ls_result_title)):

            if ll_idx == 0:

                continue

            ls_temp_body = ls_temp_body + ls_temp_body_header + str(ll_idx) + u" : " + u"""<a href=" """ + ls_result_link[ll_idx] + u""" ">""" + ls_result_title[ll_idx] + ls_temp_body_footer

        

        if return_val == None:

            return ls_temp_header + ls_temp_body + ls_temp_footer

        else:

            return_val[return_idx] = ls_temp_header + ls_temp_body + ls_temp_footer

            threadexit()


def threadexit():

    global threadsleft

    lock.acquire()

    threadsleft -= 1

    lock.release()


def main():

    

    global news_rss, threadsleft, lock, news_hosts

    news_rss = [u""]

    lock = thread.allocate_lock()


    news_hosts = [u"http://mk.co.kr.feedsportal.com/c/34147/f/618372/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618373/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618374/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618375/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618376/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618377/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618378/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618379/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618380/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618381/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/651700/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/651701/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618383/index.rss",

                  u"http://mk.co.kr.feedsportal.com/c/34147/f/618384/index.rss"]


    start = time.time()

    

    threadsleft = len(news_hosts)

    print len(news_hosts)

    

    for i in range(len(news_hosts)):

        news_rss.append(u"")

        thread.start_new_thread(SetPage, (news_hosts[i], u"TITLE", news_rss, i ))

        

    while threadsleft:

        pass


    print time.time() - start

    

    app = wx.App()

    frm = wx.Frame(None, style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER | wx.FRAME_EX_METAL, title=u"MK_RSS Reader v0.9", size=(1048,768))

    frm.CreateStatusBar()

    ico = wx.Icon(u"MK_RSS.ico", wx.BITMAP_TYPE_ICO)

    frm.SetIcon(ico)

    pnl = TestPanel(frm)

    frm.Show()

    frm.Center()

    app.MainLoop()


#----------------------------------------------------------------------

if __name__ == '__main__':

    main()


2013.10.07

#!/usr/bin/env python

#-*- coding:utf-8 -*-


import wx

import wx.html2

import urllib2

import re


news_url = u""


#----------------------------------------------------------------------

class TestPanel(wx.Panel):

    

    

    def __init__(self, parent):

        

        

        wx.Panel.__init__(self, parent)


        self.current = u"http://mk.co.kr.feedsportal.com/c/34147/f/618380/index.rss"

        self.frame = self.GetTopLevelParent()

        self.titleBase = self.frame.GetTitle()


        sizer = wx.BoxSizer(wx.VERTICAL)

        

        grpSizer = wx.BoxSizer(wx.HORIZONTAL)

        

        st1 = wx.StaticText(self, label='News Category : ')

        grpSizer.Add(st1, 0, wx.CENTER|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"경제", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoToEconomy, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"증권", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoToStock, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        btn = wx.Button(self, -1, u"부동산", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnGoToRealEState, btn)

        grpSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        

        sizer.Add(grpSizer, 0, wx.EXPAND)

        

        sizer.Add((-1, 10))

        

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)


        #btn = wx.Button(self, -1, u"Open", style=wx.BU_EXACTFIT)

        #self.Bind(wx.EVT_BUTTON, self.OnOpenButton, btn)

        #btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        btn = wx.Button(self, -1, u"<--", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnPrevPageButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        self.Bind(wx.EVT_UPDATE_UI, self.OnCheckCanGoBack, btn)


        btn = wx.Button(self, -1, u"-->", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnNextPageButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        self.Bind(wx.EVT_UPDATE_UI, self.OnCheckCanGoForward, btn)


        btn = wx.Button(self, -1, u"Stop", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnStopButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        btn = wx.Button(self, -1, u"Refresh", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnRefreshPageButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        txt = wx.StaticText(self, -1, u"Location:")

        btnSizer.Add(txt, 0, wx.CENTER|wx.ALL, 2)


        self.location = wx.ComboBox(

            self, -1, "", style=wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER)

        self.location.AppendItems([u"http://file.mk.co.kr/news/rss/rss_50300009.xml",

                                   u"http://news.mk.co.kr/rss/rss.php",

                                   u"http://www.mk.co.kr/"])


        self.Bind(wx.EVT_COMBOBOX, self.OnLocationSelect, self.location)

        self.location.Bind(wx.EVT_TEXT_ENTER, self.OnLocationEnter)

        btnSizer.Add(self.location, 1, wx.EXPAND|wx.ALL, 2)


        sizer.Add(btnSizer, 0, wx.EXPAND)

        

        sizer.Add((-1, 10))

        

        self.wv = wx.html2.WebView.New(self)

        self.Bind(wx.html2.EVT_WEBVIEW_NAVIGATING, self.OnWebViewNavigating, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_NAVIGATED, self.OnWebViewNavigated, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_LOADED, self.OnWebViewLoaded, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_TITLE_CHANGED, self.OnWebViewTitleChanged, self.wv)

        sizer.Add(self.wv, 1, wx.EXPAND)

        

        self.SetSizer(sizer)


        self.wv.LoadURL(self.current)


    # WebView events

    def OnWebViewNavigating(self, evt):

        # this event happens prior to trying to get a resource

        print u"OnWebViewNavigating URL is : %s" % evt.GetURL()

        #wx.MessageBox(evt.GetURL(), u"Target URL is...", wx.OK|wx.ICON_INFORMATION, self)

        # 1. URL이 기사 URL타입과 일치하면... 파싱 아니면 그냥 웹표시

        if (u"http://mk.co.kr.feedsportal.com/c/" in evt.GetURL()) and (not u"/index.rss" in evt.GetURL()):

            news_url = evt.GetURL()

            news_script = SetPage(evt.GetURL(), u"MK")

            self.wv.SetPage(u"<html><div>" + news_script + u"</div></html>", news_url)

            evt.Veto()

            self.current = news_url

            self.location.SetString(0, self.current)


    def OnWebViewNavigated(self, evt):

        self.frame.SetStatusText(u"Loading %s..." % evt.GetURL())


    def OnTestButton(self, evt):

        pass


    def OnWebViewLoaded(self, evt):

        # The full document has loaded

        self.current = evt.GetURL()

        if self.current == u"http:///":

            self.current = self.location.GetString(0)

            self.location.SetValue(self.location.GetString(0))

        else:

            self.location.SetValue(self.current)

        self.frame.SetStatusText(u"Loaded")

        #self.wv.RunScript("""alert('""" + self.current + """');""")

        #self.wv.RunScript("""

        #//call logIn();

        #//document.getElementsByName('q')[0].value="hist";

        #//document.getElementById('openididentifier').value="ident";

        #""")

        #self.wv.SetPage(self, """<html>하하하</html>""", """http://www.naver.com""")



    def OnWebViewTitleChanged(self, evt):

        # Set the frame's title to include the document's title

        self.frame.SetTitle("%s -- %s" % (self.titleBase, evt.GetString()))


    # Control bar events

    def OnLocationSelect(self, evt):

        url = self.location.GetStringSelection()

        print(u"OnLocationSelect: %s\n" % url)

        self.wv.LoadURL(url)


    def OnLocationEnter(self, evt):

        url = self.location.GetValue()

        self.location.Append(url)

        self.wv.LoadURL(url)


    def OnOpenButton(self, event):

        dlg = wx.TextEntryDialog(self, u"Input Url or local file path", u"URL", self.current, wx.OK|wx.CANCEL)

        dlg.CentreOnParent()


        if dlg.ShowModal() == wx.ID_OK:

            self.current = dlg.GetValue()

            self.wv.LoadURL(self.current)


        dlg.Destroy()


    def OnPrevPageButton(self, event):

        for i in self.wv.GetBackwardHistory():

            print i.Url, i.Title

        self.wv.GoBack()

        #self.wv.LoadURL(u"http://mk.co.kr.feedsportal.com/c/34147/f/618380/index.rss")


    def OnNextPageButton(self, event):

        for i in self.wv.GetForwardHistory():

            print i.URL, i.Title

        self.wv.GoForward()


    def OnCheckCanGoBack(self, event):

        event.Enable(self.wv.CanGoBack())


    def OnCheckCanGoForward(self, event):

        event.Enable(self.wv.CanGoForward())


    def OnStopButton(self, evt):

        self.wv.Stop()


    def OnRefreshPageButton(self, evt):

        self.wv.Reload()

        

    def OnGoToEconomy(self, evt):

        self.current = u"http://mk.co.kr.feedsportal.com/c/34147/f/618374/index.rss"

        self.wv.LoadURL(self.current)

        

    def OnGoToStock(self, evt):

        self.current = u"http://mk.co.kr.feedsportal.com/c/34147/f/618379/index.rss"

        self.wv.LoadURL(self.current)

        

    def OnGoToRealEState(self, evt):

        self.current = u"http://mk.co.kr.feedsportal.com/c/34147/f/618380/index.rss"

        self.wv.LoadURL(self.current)



#----------------------------------------------------------------------

def GetUrlSrc(as_url, as_decoding):

    html_src = urllib2.urlopen(as_url).read()

    return html_src.decode(as_decoding, 'ignore')


def SetPage(as_url, as_site):

    # 1. URL이 기사 URL타입과 일치하면... 파싱 아니면 그냥 웹표시

    if as_site == u"MK":

        script_pattern = "<div\sclass=\'read_txt\'>(.*?)\s*?<!--이미지".decode("utf-8", "ignore")

        result_html = GetUrlSrc(as_url, u"cp949")

        #wx.MessageBox(result_html, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        result_text = re.findall(script_pattern, result_html, re.DOTALL)

        if result_text:

            #wx.MessageBox(result_text[0], u"Test", wx.OK|wx.ICON_INFORMATION, self)

            #ls_return = " ".join(str(re.sub("<[^>]*>".decode("utf-8", "ignore"), "".decode("utf-8", "ignore"), result_text[0]).encode("cp949", "ignore")).split())

            #wx.MessageBox(result_text[0], u"News", wx.OK|wx.ICON_INFORMATION)

            return result_text[0]


def main():

    app = wx.App()

    frm = wx.Frame(None, style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER | wx.FRAME_EX_METAL, title=u"MK_RSS Reader v0.9", size=(1048,768))

    frm.CreateStatusBar()

    pnl = TestPanel(frm)

    frm.Show()

    frm.Center()

    app.MainLoop()


#----------------------------------------------------------------------

if __name__ == '__main__':

    main()


2013.10.06

#!/usr/bin/env python

#-*- coding:utf-8 -*-


import wx

import wx.html2

import urllib2

import re


#----------------------------------------------------------------------

class TestPanel(wx.Panel):

    def __init__(self, parent):

        wx.Panel.__init__(self, parent)


        self.current = u"http://file.mk.co.kr/news/rss/rss_50300009.xml"

        self.frame = self.GetTopLevelParent()

        self.titleBase = self.frame.GetTitle()


        sizer = wx.BoxSizer(wx.VERTICAL)

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)


        self.wv = wx.html2.WebView.New(self)

        self.Bind(wx.html2.EVT_WEBVIEW_NAVIGATING, self.OnWebViewNavigating, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_NAVIGATED, self.OnWebViewNavigated, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_LOADED, self.OnWebViewLoaded, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_TITLE_CHANGED, self.OnWebViewTitleChanged, self.wv)


        btn = wx.Button(self, -1, "Open", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnOpenButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        btn = wx.Button(self, -1, "<--", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnPrevPageButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        self.Bind(wx.EVT_UPDATE_UI, self.OnCheckCanGoBack, btn)


        btn = wx.Button(self, -1, "-->", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnNextPageButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        self.Bind(wx.EVT_UPDATE_UI, self.OnCheckCanGoForward, btn)


        btn = wx.Button(self, -1, "Stop", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnStopButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        btn = wx.Button(self, -1, "Refresh", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnRefreshPageButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        txt = wx.StaticText(self, -1, "Location:")

        btnSizer.Add(txt, 0, wx.CENTER|wx.ALL, 2)


        self.location = wx.ComboBox(

            self, -1, "", style=wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER)

        self.location.AppendItems(['http://wxPython.org',

                                   'http://wxwidgets.org',

                                   'http://google.com'])


        self.Bind(wx.EVT_COMBOBOX, self.OnLocationSelect, self.location)

        self.location.Bind(wx.EVT_TEXT_ENTER, self.OnLocationEnter)

        btnSizer.Add(self.location, 1, wx.EXPAND|wx.ALL, 2)


        sizer.Add(btnSizer, 0, wx.EXPAND)

        sizer.Add(self.wv, 1, wx.EXPAND)

        self.SetSizer(sizer)


        self.wv.LoadURL(self.current)


    # WebView events

    def OnWebViewNavigating(self, evt):

        # this event happens prior to trying to get a resource

        print u"Target URL is : %s" % evt.GetURL()

        #wx.MessageBox(evt.GetURL(), u"Target URL is...", wx.OK|wx.ICON_INFORMATION, self)

        # 1. URL이 기사 URL타입과 일치하면... 파싱 아니면 그냥 웹표시

        if u"http://mk.co.kr.feedsportal.com/c/" in evt.GetURL():

            news_script = SetPage(evt.GetURL(), u"MK")

            print type(news_script)

            self.wv.SetPage(u"<html><div>" + news_script + u"</div></html>", "")

            evt.Veto()


    def OnWebViewNavigated(self, evt):

        self.frame.SetStatusText("Loading %s..." % evt.GetURL())


    def OnTestButton(self, evt):

        pass


    def OnWebViewLoaded(self, evt):

        # The full document has loaded

        self.current = evt.GetURL()

        self.location.SetValue(self.current)

        self.frame.SetStatusText("Loaded")

        #self.wv.RunScript("""alert('""" + self.current + """');""")

        #self.wv.RunScript("""

        #//call logIn();

        #//document.getElementsByName('q')[0].value="hist";

        #//document.getElementById('openididentifier').value="ident";

        #""")

        #self.wv.SetPage(self, """<html>하하하</html>""", """http://www.naver.com""")



    def OnWebViewTitleChanged(self, evt):

        # Set the frame's title to include the document's title

        self.frame.SetTitle("%s -- %s" % (self.titleBase, evt.GetString()))


    # Control bar events

    def OnLocationSelect(self, evt):

        url = self.location.GetStringSelection()

        print('OnLocationSelect: %s\n' % url)

        self.wv.LoadURL(url)


    def OnLocationEnter(self, evt):

        url = self.location.GetValue()

        self.location.Append(url)

        self.wv.LoadURL(url)


    def OnOpenButton(self, event):

        dlg = wx.TextEntryDialog(self, "Open Location",

                                "Enter a full URL or local path",

                                self.current, wx.OK|wx.CANCEL)

        dlg.CentreOnParent()


        if dlg.ShowModal() == wx.ID_OK:

            self.current = dlg.GetValue()

            self.wv.LoadURL(self.current)


        dlg.Destroy()


    def OnPrevPageButton(self, event):

        #for i in self.wv.GetBackwardHistory():

        #    print i.Url, i.Title

        #self.wv.GoBack()

        self.wv.LoadURL(u"http://file.mk.co.kr/news/rss/rss_50300009.xml")


    def OnNextPageButton(self, event):

        #for i in self.wv.GetForwardHistory():

        #    print i.URL, i.Title

        self.wv.GoForward()


    def OnCheckCanGoBack(self, event):

        event.Enable(self.wv.CanGoBack())


    def OnCheckCanGoForward(self, event):

        event.Enable(self.wv.CanGoForward())


    def OnStopButton(self, evt):

        self.wv.Stop()


    def OnRefreshPageButton(self, evt):

        self.wv.Reload()



#----------------------------------------------------------------------

def GetUrlSrc(as_url, as_decoding):

    html_src = urllib2.urlopen(as_url).read()

    return html_src.decode(as_decoding, 'ignore')


def SetPage(as_url, as_site):

    # 1. URL이 기사 URL타입과 일치하면... 파싱 아니면 그냥 웹표시

    if as_site == u"MK":

        script_pattern = "<div\sclass=\'read_txt\'>(.*?)\s*?<!--이미지".decode("utf-8", "ignore")

        result_html = GetUrlSrc(as_url, u"cp949")

        #wx.MessageBox(result_html, u"Test", wx.OK|wx.ICON_INFORMATION, self)

        result_text = re.findall(script_pattern, result_html, re.DOTALL)

        if result_text:

            #wx.MessageBox(result_text[0], u"Test", wx.OK|wx.ICON_INFORMATION, self)

            #ls_return = " ".join(str(re.sub("<[^>]*>".decode("utf-8", "ignore"), "".decode("utf-8", "ignore"), result_text[0]).encode("cp949", "ignore")).split())

            #wx.MessageBox(result_text[0], u"News", wx.OK|wx.ICON_INFORMATION)

            return result_text[0]


def main():

    app = wx.App()

    frm = wx.Frame(None, style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER | wx.FRAME_EX_METAL, title=u"MK_RSS Reader v0.9", size=(1048,768))

    frm.CreateStatusBar()

    pnl = TestPanel(frm)

    frm.Show()

    frm.Center()

    app.MainLoop()


#----------------------------------------------------------------------

if __name__ == '__main__':

    main()


'Study > python' 카테고리의 다른 글

[연습]AutoPOKO ~~  (0) 2013.11.11
[펌]python thread 사용예  (0) 2013.10.16
wxpython webview test  (0) 2013.10.05
[연습중]MK RSS 파싱  (0) 2013.09.23
[연습]손바닥삼국지 오토  (0) 2013.09.22
Posted by 땡보
2013. 10. 5. 09:39


#!/usr/bin/env python

#-*- coding:utf-8 -*-


import wx

import wx.html2


#----------------------------------------------------------------------


class TestPanel(wx.Panel):

    def __init__(self, parent):

        wx.Panel.__init__(self, parent)


        self.current = "http://www.google.com"

        self.frame = self.GetTopLevelParent()

        self.titleBase = self.frame.GetTitle()


        sizer = wx.BoxSizer(wx.VERTICAL)

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)

        self.wv = wx.html2.WebView.New(self)

        self.Bind(wx.html2.EVT_WEBVIEW_NAVIGATING, self.OnWebViewNavigating, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_NAVIGATED, self.OnWebViewNavigated, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_LOADED, self.OnWebViewLoaded, self.wv)

        self.Bind(wx.html2.EVT_WEBVIEW_TITLE_CHANGED, self.OnWebViewTitleChanged, self.wv)


        btn = wx.Button(self, -1, "Open", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnOpenButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        btn = wx.Button(self, -1, "<--", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnPrevPageButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        self.Bind(wx.EVT_UPDATE_UI, self.OnCheckCanGoBack, btn)


        btn = wx.Button(self, -1, "-->", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnNextPageButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)

        self.Bind(wx.EVT_UPDATE_UI, self.OnCheckCanGoForward, btn)


        btn = wx.Button(self, -1, "Stop", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnStopButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        btn = wx.Button(self, -1, "Refresh", style=wx.BU_EXACTFIT)

        self.Bind(wx.EVT_BUTTON, self.OnRefreshPageButton, btn)

        btnSizer.Add(btn, 0, wx.EXPAND|wx.ALL, 2)


        txt = wx.StaticText(self, -1, "Location:")

        btnSizer.Add(txt, 0, wx.CENTER|wx.ALL, 2)


        self.location = wx.ComboBox(

            self, -1, "", style=wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER)

        self.location.AppendItems(['http://wxPython.org',

                                   'http://wxwidgets.org',

                                   'http://google.com'])


        #for url in ['http://wxPython.org',

        #            'http://wxwidgets.org',

        #            'http://google.com']:

        #    item = webview.WebViewHistoryItem(url, url)

        #    self.wv.LoadHistoryItem(item)


        self.Bind(wx.EVT_COMBOBOX, self.OnLocationSelect, self.location)

        self.location.Bind(wx.EVT_TEXT_ENTER, self.OnLocationEnter)

        btnSizer.Add(self.location, 1, wx.EXPAND|wx.ALL, 2)



        sizer.Add(btnSizer, 0, wx.EXPAND)

        sizer.Add(self.wv, 1, wx.EXPAND)

        self.SetSizer(sizer)


        self.wv.LoadURL(self.current)




    # WebView events

    def OnWebViewNavigating(self, evt):

        # this event happens prior to trying to get a resource

        if evt.GetURL() == 'http://www.microsoft.com/':

            if wx.MessageBox("Are you sure you want to visit Microsoft?",

                             style=wx.YES_NO|wx.ICON_QUESTION) == wx.NO:

                # This is how you can cancel loading a page.

                evt.Veto()



    def OnWebViewNavigated(self, evt):

        self.frame.SetStatusText("Loading %s..." % evt.GetURL())



    def OnWebViewLoaded(self, evt):

        # The full document has loaded

        if u'about:blank' in evt.GetURL():

            return -1

        self.current = evt.GetURL()

        self.location.SetValue(self.current)

        self.frame.SetStatusText("Loaded")

        self.wv.RunScript("""

        document.getElementsByName('q')[0].value="hist";

        //document.getElementById('openididentifier').value="ident";

        //document.getElementsByName('login')[1].click()

        """)



    def OnWebViewTitleChanged(self, evt):

        # Set the frame's title to include the document's title

        self.frame.SetTitle("%s -- %s" % (self.titleBase, evt.GetString()))



    # Control bar events

    def OnLocationSelect(self, evt):

        url = self.location.GetStringSelection()

        print('OnLocationSelect: %s\n' % url)

        self.wv.LoadURL(url)


    def OnLocationEnter(self, evt):

        url = self.location.GetValue()

        self.location.Append(url)

        self.wv.LoadURL(url)



    def OnOpenButton(self, event):

        dlg = wx.TextEntryDialog(self, "Open Location",

                                "Enter a full URL or local path",

                                self.current, wx.OK|wx.CANCEL)

        dlg.CentreOnParent()


        if dlg.ShowModal() == wx.ID_OK:

            self.current = dlg.GetValue()

            self.wv.LoadURL(self.current)


        dlg.Destroy()


    def OnPrevPageButton(self, event):

        for i in self.wv.GetBackwardHistory():

            print i.Url, i.Title

        self.wv.GoBack()


    def OnNextPageButton(self, event):

        for i in self.wv.GetForwardHistory():

            print i.URL, i.Title

        self.wv.GoForward()


    def OnCheckCanGoBack(self, event):

        event.Enable(self.wv.CanGoBack())


    def OnCheckCanGoForward(self, event):

        event.Enable(self.wv.CanGoForward())


    def OnStopButton(self, evt):

        self.wv.Stop()


    def OnRefreshPageButton(self, evt):

        self.wv.Reload()



#----------------------------------------------------------------------



def main():

    app = wx.App()

    frm = wx.Frame(None, style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER | wx.FRAME_EX_METAL, title="html2.WebView sample", size=(700,500))

    frm.CreateStatusBar()

    pnl = TestPanel(frm)

    frm.Show()

    app.MainLoop()



#----------------------------------------------------------------------


if __name__ == '__main__':

    main()


'Study > python' 카테고리의 다른 글

[펌]python thread 사용예  (0) 2013.10.16
[연습]wxpython rss reader  (0) 2013.10.06
[연습중]MK RSS 파싱  (0) 2013.09.23
[연습]손바닥삼국지 오토  (0) 2013.09.22
[연습]Python regular expression & sqlite  (0) 2013.09.22
Posted by 땡보
2013. 9. 23. 10:57

#AutoIt3Wrapper_icon=AutoㅇㅇㅇㅇLecture.ico


; 목적 : AutoIt 학습 및 imagesearch 라이브러리 사용법 학습

; 버전 : 3.3.8.1

; 일자 : 2013.06월의 어느날

; 동작 :

; ㅇㅇㅇㅇ 사내 산업안전교육 온라인 교육 및 시험을 자동으로 수강 및 응시한다.


#include <ImageSearch.au3>


Global $gs_mainwintitle = "ㅇㅇㅇㅇ㈜"

Global $gs_lecwintitle = "교안보기..."

Global $gs_googledef = "Google 계정"

Global $gs_chromedef = "- Chrome"

Global $ghWnd_MWin = 0

Global $gs_userid = ""

Global $gs_userpw = ""

Global $gl_maxleccnt = 5

Global $gl_limitsec = 1210

Global $gpos_basex1 = 0

Global $gpos_basey1 = 0

Global $Paused

Global $gl_tolerance = 0


If MutexExists("ㅇㅇㅇㅇOnlineLecture") Then

MsgBox(0, "알림", "자동수강이 이미 실행 중입니다.")

ToolTip("")

Exit

EndIf


Func MutexExists($sOccurenceName)

Local $ERROR_ALREADY_EXISTS = 183, $handle, $lastError

$sOccurenceName = StringReplace($sOccurenceName, "", "")

$handle = DllCall("kernel32.dll", "int", "CreateMutex", "int", 0, "long", 1, "str", $sOccurenceName)

$lastError = DllCall("kernel32.dll", "int", "GetLastError")

Return $lastError[0] = $ERROR_ALREADY_EXISTS

EndFunc


HotKeySet("{ESC}", "ExitForce")

HotKeySet("+!p", "TogglePause")


ToolTip("산업안전 자동수강 실행중...", 0, 0)


If FileExists(@ProgramFilesDir & "\Google\Chrome\Application\chrome.exe") Then

If MsgBox(4,"알림", "ㅇㅇㅇㅇ 온라인 법정안전교육 자동수강을 시작하시겠습니까?" & @CRLF & _

                        "(모든 강의를 수강하신 후 이 프로그램을 재실행 하시면" & @CRLF & " 자동 시험응시가 가능합니다!!)") == 6 Then


While 1

$gl_tolerance = InputBox("입력", "이미지 검색 오차범위를 설정하여 주세요.(1~10사이숫자범위)" & @CRLF & @CRLF & "검색 오차범위는 프로그램이 창을 찾지 못하면 높게 잡아주세요!!" & @CRLF & @CRLF &"오차범위가 낮을수록 프로그램 정확도가 올라갑니다!!" & @CRLF & "(3정도가 가장 좋은 인식율을 보이는것 같습니다)",3,"",400,250)

If $gl_tolerance == "" Then

If MsgBox(4, "입력", "프로그램을 실행을 중지하시겠습니까?") == 6 Then

ToolTip("")

Exit

EndIf

EndIf


If $gl_tolerance < 1 or  $gl_tolerance > 10 Then

MsgBox(0, "알림", "1~10 사이 숫자만 입력가능합니다!!")

Else

ExitLoop

EndIf

WEnd

Main()

Else

MsgBox(0, "알림", "사용자 요청으로 자동수강을 종료합니다!!", 3)

ToolTip("")

Exit

EndIf

Else

If MsgBox(4, "알림", "크롬 브라우저가 설지되어 있지 않습니다!!" & @CRLF & "자동수강은 크롬 브라우저가 설치되어 있어야 정상 동작합니다!!" & @CRLF & "크롬 브라우저를 설치하시겠습니까?") == 6 Then

$ll_retval = ShellExecute("explorer.exe", "http://www.google.com/intl/ko/chrome/browser/")

If $ll_retval == 1 Then

MsgBox(0, "알림", "멋진 선택이십니다. 크롬 설치후 다시한번 실행하여 주세요!!")

ToolTip("")

Exit

Else

MsgBox(0, "알림", "알수없는 오류로 인하여 크롬브라우저 설치 진행에 실패하였습니다!! 아쉽지만 다음기회에....")

ToolTip("")

Exit

EndIf

Else

MsgBox(0, "알림", "크롬브라우저가 없어 진행을 종료합니다!!")

ToolTip("")

Exit

EndIf

EndIf


Func Main()


$lpos_x1 = 0

$lpos_y1 = 0


$ll_retval = 0


    While ProcessExists("chrome.exe")

        ProcessClose("chrome.exe")

    WEnd


Close_ExistWindow($gs_mainwintitle)

Close_ExistWindow($gs_lecwintitle)


$ghWnd_MWin = Find_Window($gs_mainwintitle)


If $ghWnd_MWin < 0 Then

MsgBox(0, "알림", "ㅇㅇㅇㅇ 온라인 법정안전교육 창을 찾지 못했습니다!!")

ToolTip("")

Exit

EndIf


$ll_retval = WinMove($ghWnd_MWin,"", 0,0,1024,768)


If $ll_retval == 0 Then

MsgBox(0, "알림", "ㅇㅇㅇㅇ 온라인 법정안전교육 창을 찾지 못했습니다!!")

ToolTip("")

Exit

EndIf


Activate_MainWin($ghWnd_MWin)

$ll_retval = _WaitForImageSearch("GoogleDef.bmp",3,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval == 1 Then

Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_x1+85,$lpos_y1)

Sleep(100)

MouseClick("left")

EndIf


Activate_MainWin($ghWnd_MWin)

$ll_retval = _WaitForImageSearch("ChromeDef.bmp",3,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval == 1 Then

Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_x1,$lpos_y1)

Sleep(100)

MouseClick("left")

EndIf


Activate_MainWin($ghWnd_MWin)

$ll_retval = _WaitForImageSearch("LectureDef.bmp",3,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval == 1 Then

Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_x1,$lpos_y1)

Sleep(100)

MouseClick("left")

EndIf


Activate_MainWin($ghWnd_MWin)


Input_UserInfo()


Login_Site()


GoToLectureRoom()


WatchLecture()


EndFunc


Func GetBasePosition()

$lpos_x1 = 0

$lpos_y1 = 0

$lpos = 0


Activate_MainWin($ghWnd_MWin)

$ll_retval =  _WaitForImageSearch("BasePosition.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval <> 1 Then

MsgBox(0,"알림", "시험답안지 기준점을 찾는데 실패하였습니다" & @CRLF & "프로그램을 종료합니다!!")

ToolTip("")

Exit

EndIf

MouseMove($lpos_x1, $lpos_y1)

$lpos = MouseGetPos()

$gpos_basex1 = $lpos[0] + 1

$gpos_basey1 = $lpos[1] + 3

;MsgBox(0, "알림", "Mouse x,y:" & $pos[0] & "," & $pos[1])

EndFunc


Func AnswerSheetMatrix($al_ques_no, $al_answ_no, ByRef $apos_x1, ByRef $apos_y1)

$lpos_x1 = $gpos_basex1

If $al_ques_no <= 6 Then

$lpos_y1 = $gpos_basey1

Else

$al_ques_no = $al_ques_no - 7

$lpos_y1 = $gpos_basey1 + 316

EndIf


$apos_x1 = $lpos_x1 + (41 * $al_answ_no)

$apos_y1 = $lpos_y1 + (57 * $al_ques_no)

EndFunc


Func EnterExam()

Dim $larray_answer[11] = [0,4,4,4,2,1,4,2,3,4,3]


$lpos_x1 = 0

$lpos_y1 = 0

Activate_MainWin($ghWnd_MWin)

$ll_retval =  _WaitForImageSearch("ExamSeason.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval <> 1 Then

MsgBox(0,"알림", "3분기 근로자 정기교육만 자동응시 가능합니다!!" & @CRLF & "프로그램을 종료합니다!!")

ToolTip("")

Exit

EndIf

Activate_MainWin($ghWnd_MWin)

$ll_retval =  _WaitForImageSearch("EnterExam01.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval <> 1 Then

Activate_MainWin($ghWnd_MWin)

$ll_retval =  _WaitForImageSearch("EnterExam02.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

EndIf


If $ll_retval <> 1 Then

MsgBox(0,"알림", "응시할 시험이 없습니다!!" & @CRLF & "프로그램을 종료합니다!!")

ToolTip("")

Exit

EndIf


Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_x1,$lpos_y1)

Sleep(1000)

MouseClick("left")

Sleep(1000)

MouseMove(0,0)


For $i = 1 To 6

Send("{RIGHT}")

Sleep(50)

Next


Activate_MainWin($ghWnd_MWin)

$ll_retval =  _WaitForImageSearch("AnswerSheet.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)


If $ll_retval <> 1 Then

MsgBox(0,"알림", "답안지를 찾을 수 없습니다!!" & @CRLF & "프로그램을 종료합니다!!")

ToolTip("")

Exit

EndIf


GetBasePosition()


Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_x1,$lpos_y1)

Sleep(100)

MouseClick("left")

$lpos_basex1 = $lpos_x1

$lpos_basey1 = $lpos_y1


For $i = 1 To UBound($larray_answer) - 1

If $i == 8 Then

Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_basex1,$lpos_basey1)

Sleep(50)

MouseClick("left")

For $j = 1 To 3

Activate_MainWin($ghWnd_MWin)

Send("{DOWN}")

Sleep(50)

Next

EndIf


AnswerSheetMatrix($i - 1, $larray_answer[$i] - 1, $lpos_x1, $lpos_y1)

Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_x1,$lpos_y1)

Sleep(100)

MouseClick("left")

Sleep(100)

Next


Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_basex1,$lpos_basey1)

Sleep(50)

MouseClick("left")

For $j = 1 To 3

Activate_MainWin($ghWnd_MWin)

Send("{DOWN}")

Sleep(50)

Next


Activate_MainWin($ghWnd_MWin)

$ll_retval =  _WaitForImageSearch("Submit.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval <> 1 Then

MsgBox(0,"알림", "제출버튼을 찾을 수 없습니다!!" & @CRLF & "수동으로 제출해주세요!!")

EndIf


Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_x1,$lpos_y1)

Sleep(100)

MouseClick("left")


Activate_MainWin($ghWnd_MWin)

$ll_retval =  _WaitForImageSearch("Confirm.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval <> 1 Then

MsgBox(0,"알림", "제출버튼을 찾을 수 없습니다!!" & @CRLF & "수동으로 제출해주세요!!")

EndIf


Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_x1,$lpos_y1)

Sleep(100)

MouseClick("left")


MsgBox(0, "알림", "시험 응시가 끝났습니다!! 쌍콤한 하루 되세요~")

ToolTip("")

Exit

EndFunc


Func WatchLecture()

$lpos_x1 = 0

$lpos_y1 = 0

$ll_errcnt = 0


$idx_lec = 1

While 1

Activate_MainWin($ghWnd_MWin)

$ll_retval =  _WaitForImageSearch("Completing.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval <> 1 Then

Activate_MainWin($ghWnd_MWin)

$ll_retval =  _WaitForImageSearch("NotComplete.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

EndIf

If $ll_retval == 1 Then

$lpos_x1 = $lpos_x1 - 330

Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_x1,$lpos_y1)

Sleep(1000)

MouseClick("left")

Sleep(2000)

MouseMove(0,0)

$ll_retval = WinSetState($ghWnd_MWin, "", @SW_MINIMIZE)

$ll_retval = WinExists($gs_lecwintitle)

If $ll_retval == 1 Then

$lhWnd_LecWin = WinGetHandle($gs_lecwintitle)

$ll_retval = WinMove($lhWnd_LecWin,"", 0,0,1024,768)

$ll_retval = WinSetState($lhWnd_LecWin, "", @SW_MINIMIZE)


$ls_msg = ""


ProgressOn("자동수강 진행사항", String($idx_lec) & "차시 강의 " & "0% 수강중...(다른작업 가능합니다.)", "")


$ll_watchrate = 0


; 테스트 30초 수강!!

;$gl_limitsec = 10

For $ll_remainsec = 1 To $gl_limitsec

$ll_watchrate = Round(($ll_remainsec / $gl_limitsec) * 100, 0)

$ls_msg = "중지:ESC / 일시정지:Alt+Shift+p"

$ll_retval = WinExists($lhWnd_LecWin)

If $ll_retval <> 1 Then

ProgressOff()

MsgBox(0, "알림", "강의창이 사라져 자동수강을 종료합니다!!")

ToolTip("")

Exit

EndIf

ProgressSet($ll_watchrate, String($ll_watchrate) & "% 수강중...(다른작업 가능합니다.)", $ls_msg)

Sleep(1000)

Next


ProgressSet(100, "강의 100% 수강완료!!", $ls_msg)

Sleep(500)

ProgressOff()


WinClose($lhWnd_LecWin)


$idx_lec = $idx_lec + 1


If $idx_lec > $gl_maxleccnt Then

ExitLoop

EndIf

Else

MsgBox(0,"알림","미수강 강의 리스트를 찾지 못하였습니다!!" & @CRLF & "3초후 강의를 재탐색 합니다!!", 3)

WinClose($gs_lecwintitle)

$ll_errcnt = $ll_errcnt + 1

If $ll_errcnt >= 3 Then

MsgBox(0, "알림", "더이상 수강 가능한 강의를 찾을 수 없어 프로그램을 종료 합니다!!")

ToolTip("")

Exit

EndIf

EndIf

Else

MsgBox(0,"알림","미수강 강의 리스트를 찾지 못하였습니다!!" & @CRLF & "3초후 강의를 재탐색 합니다!!", 3)

WinClose($gs_lecwintitle)

$ll_errcnt = $ll_errcnt + 1

If $ll_errcnt >= 3 Then

MsgBox(0, "알림", "더이상 수강 가능한 강의를 찾을 수 없어 프로그램을 종료 합니다!!")

ToolTip("")

Exit

EndIf

EndIf

WEnd

EndFunc


Func GoToLectureRoom()

$lpos_x1 = 0

$lpos_y1 = 0


Activate_MainWin($ghWnd_MWin)

For $i = 1 To 3


If $i == 3 Then

Activate_MainWin($ghWnd_MWin)

$ll_retval =  _WaitForImageSearch("PossibleExam01.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval == 1 Then

If MsgBox(4, "알림", "이미 모든 강의를 수강하셨습니다!! 시험에 응시 하시겠습니까?") == 6 Then

EnterExam()

ToolTip("")

Exit

EndIf

EndIf

EndIf


Activate_MainWin($ghWnd_MWin)

$ll_retval =  _WaitForImageSearch("ClassRoom0" & String($i) & ".bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval == 1 Then

Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_x1,$lpos_y1)

Sleep(1000)

MouseClick("left")

Sleep(1000)

Else

MsgBox(0,"알림","강의실 바로가기를 찾지 못하였습니다!!")

ToolTip("")

Exit

EndIf

Next

EndFunc


Func Activate_MainWin($ahWnd_Win)

$ll_retval = WinActivate($ahWnd_Win)

MouseMove(0,0)

If $ll_retval == 0 Then

MsgBox(0, "알림", "ㅇㅇㅇㅇ 온라인 법정안전교육 창을 찾지 못했습니다!!")

ToolTip("")

Exit

EndIf

EndFunc


Func Login_Site()

$lpos_x1 = 0

$lpos_y1 = 0


Activate_MainWin($ghWnd_MWin)


$ll_retval = _WaitForImageSearch("Logout.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

if $ll_retval == 1 Then

MouseMove($lpos_x1-55,$lpos_y1+19)

Sleep(1000)

MouseClick("left")

Sleep(3000)

EndIf


$lpos_x1 = 0

$lpos_y1 = 0


$ll_retval = _WaitForImageSearch("Login.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval == 1 Then

Activate_MainWin($ghWnd_MWin)

MouseMove($lpos_x1,$lpos_y1-12,1)

MouseClick("left")

Send($gs_userid)

Sleep(500)

Send("{Enter}")

Sleep(500)

Send("{Tab}")

Sleep(500)

Send($gs_userpw)

Send("{Enter}")

$ll_retval = _WaitForImageSearch("Loginfail.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

If $ll_retval == 1 Then

Close_ExistWindow($gs_mainwintitle)

MsgBox(0, "알림", "입력하신 ID 또는 PW가 올바르지 않습니다!!" & @CRLF & "확인 후 다시 시도하여 주세요!!")

ToolTip("")

Exit

EndIf

Else

MsgBox(0,"알림","로그인창을 찾지 못하였습니다!!")

ToolTip("")

Exit

EndIf

EndFunc


Func Input_UserInfo()

$gs_userid = ""

$gs_userpw = ""


$gs_userid = InputBox("입력", "교육대상자 ID를 입력!!" & @CRLF & "(그룹웨어ID[사번아님]})")

$gs_userpw = InputBox("입력", "교육대상자 비밀번호 입력!!" & @CRLF & "(기본패스워드 1111)", "", "*")


If $gs_userid == "" Or $gs_userpw == "" Then

If MsgBox(4, "알림", "교육대상자 ID 또는 패스워드가 올바르지 않습니다!!" & @CRLF & "다시 입력하시겠습니까?") == 6 Then

Input_UserInfo()

Else

MsgBox(0, "알림", "프로그램을 종료합니다!!",5)

ToolTip("")

Exit

EndIf

Else

Return 1

EndIf

EndFunc


Func Find_Window($as_wintitle)

$ll_retval = 0


$ll_retval = WinExists($as_wintitle)


If $ll_retval == 1 Then

Return WinGetHandle($as_wintitle)

Else

$ll_retval = ShellExecute("chrome.exe", "--incognito http://ㅇㅇㅇㅇ.산업안전보건교육.kr/")

If $ll_retval == 1 Then

Sleep(2000)

Return WinGetHandle($as_wintitle)

Else

Return -1

EndIf

EndIf

EndFunc


Func Close_ExistWindow($as_wintitle)


While 1

$lhWnd_temp = 0

$ll_retval = 0

$lpos_x1 = 0

$lpos_y1 = 0


$ll_retval = WinExists($as_wintitle)


If $ll_retval == 1 Then

$lhWnd_temp = WinGetHandle($as_wintitle)

Activate_MainWin($lhWnd_temp)

Sleep(500)


$ll_retval = WinMove($lhWnd_temp,"", 0,0,1024,768)

If $ll_retval == 0 Then

MsgBox(0, "알림", "ㅇㅇㅇㅇ 온라인 법정안전교육 창을 찾지 못했습니다!!")

ToolTip("")

Exit

EndIf

$ll_retval = _WaitForImageSearch("Logout.bmp",5,1,$lpos_x1,$lpos_y1,$gl_tolerance)

if $ll_retval == 1 Then

MouseMove($lpos_x1-55,$lpos_y1+19)

Sleep(500)

MouseClick("left")

Sleep(1000)

EndIf

WinClose($lhWnd_temp)

Else

ExitLoop

EndIf

WEnd


EndFunc


Func ExitForce()

If MsgBox(4,"알림", "ㅇㅇㅇㅇ 온라인 법정안전교육 자동수강을 강제 종료 하시겠습니까?") == 6 Then

ToolTip("")

Exit

EndIf

EndFunc


Func TogglePause()

    $Paused = Not $Paused

    While $Paused

        Sleep(100)

        ToolTip("자동수강 일시정지중...", -1, -1)

    WEnd

    ToolTip("자동수강 진행중....", -1, -1)

EndFunc


'Study > AutoIt/AutoHotKey' 카테고리의 다른 글

[펌]Alternative to _StringEncrypt()  (0) 2013.07.29
Posted by 땡보
2013. 9. 23. 06:42

'Study > python' 카테고리의 다른 글

[연습]wxpython rss reader  (0) 2013.10.06
wxpython webview test  (0) 2013.10.05
[연습]손바닥삼국지 오토  (0) 2013.09.22
[연습]Python regular expression & sqlite  (0) 2013.09.22
[펌]Unicode In Python, Completely Demystified  (0) 2013.09.18
Posted by 땡보
2013. 9. 22. 15:53

본 소스 코드는 개인 학습용으로 연습삼아 작성한 코드 입니다.

또한 2012년 작성 코드로 현재 동작 여부는 알 수 없습니다.

혹시나 퍼가셔서 사용하시거나, 또는 수정하여 사용하시다 발생하는 모든 책임은 사용자 본인에게 있음을 알려드립니다.

#!/usr/bin/env python

#-*- coding:ms949 -*-


'''

    목  적 : Python 정규식 및 urllib 연습

    버  전 : Python 3.2

    연습일 : 2012.04.16

    동  작 :

    모바일 게임 어플인 '손바닥삼국지'를 자동으로 플레이 해준다.

'''

import time

import http.client

import urllib.parse

import re

import random

import sys

import os

import copy


base_user_id   = ''

base_user_pw   = ''

base_user_host = 'k5.tapsg.com'

base_cookie    = ''

base_token     = ''

base_city_id   = ''

city_id_all    = ''

base_max_cnt   = 500                    #오랑캐 최대 검색 좌표수(섭 트레픽 증가로 인한 계정 블럭을 방지)

base_find_cnt  = 100

base_find_type = 3                      #찾고 싶은 오랑캐 타입(별!!! 카운트 내림차수 정렬임!!)


def chk_auth():

    get_auth_url =  '/auth.html'

    html_source = get_html_response(get_auth_url, 3)

    if html_source == '::ERROR::':

        sys.exit()

    if '"code":0' in html_source:

        #print('실행 장소 인증 성공')

        return

    else:

        print('허가되지 않은 장소에서의실행 요청입니다!!')

        sys.exit()


def auto_attack(city_id, inteval_sec, type_orang, type_soldier, num_soldier):

    next_ip             = 'next'

    err_cnt             = 0

    food_per_attack     = 0

    interval_per_attack = 0

    city_tot_money      = 0

    city_tot_food       = 0

    need_chg_tot_gold   = 0


    while True:

        # 도시정보 호출 후 식량자원량 추출

        city_resource = get_city_resource(city_id)

        if city_resource:

            if city_resource == '::ERROR::':

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[01]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1

            else:

                city_tot_money = city_resource[0][0]

                city_tot_food  = city_resource[0][1]

                next_ip = 'next'

                rand_timesleep()                

        else:

            if err_cnt <= 3:

                err_cnt += 1

                print('[02]Error발생')

                timesleep(5)

                continue

            else:

                print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                return -1

        

        if next_ip == 'next':

            # 1. 목록(의미없음)

            # GET /game/api_fav.php?jsonpcallback=jsonp1334359483814&_=1334372334923&key=ac91d18916be985c476e6a4bbfb7bd56&_l=kr&_p=SG-IPHONE-KR HTTP/1.1

            # jsonp1334423944539({"code":0,"ret":{"friend":[{"id":6800,"nick":"harddisk","nationid":2,"level":57,"guild":"\uace0\ud55c\uc74d","guildid":13,"gpower":5,"gflag":64,"protection":0,"status":0,"conq":[0,0,null]},{"id":19762,"nick":"shoowhip","nationid":2,"level":37,"guild":"\uace0\ud55c\uc74d","guildid":13,"gpower":5,"gflag":64,"protection":0,"status":0,"conq":[0,0,null]},{"id":19788,"nick":"\uac81\ud608\uc774","nationid":1,"level":50,"guild":"\uace0\ud55c\uc74d","guildid":13,"gpower":5,"gflag":64,"protection":0,"status":0,"conq":[0,0,null]},{"id":19794,"nick":"chakani710","nationid":3,"level":47,"guild":"\uace0\ud55c\uc74d","guildid":13,"gpower":5,"gflag":64,"protection":0,"status":0,"conq":[0,0,null]},{"id":20424,"nick":"sphere604","nationid":1,"level":47,"guild":"\uace0\ud55c\uc74d","guildid":13,"gpower":5,"gflag":64,"protection":0,"status":0,"conq":[0,0,null]},{"id":20834,"nick":"\uad00\uc6b0\uc6b4\uc7a5","nationid":1,"level":20,"guild":"\uc2ed\uc790\uad70","guildid":58,"gpower":5,"gflag":68,"protection":0,"status":0,"conq":[0,0,null]},{"id":21006,"nick":"abcd1004","nationid":1,"level":12,"guild":"","guildid":0,"gpower":0,"gflag":1,"protection":0,"status":0,"conq":[0,0,null]},{"id":21045,"nick":"\uac00\ub294\ube44\uc628\ub2e4","nationid":2,"level":34,"guild":"","guildid":0,"gpower":0,"gflag":1,"protection":0,"status":0,"conq":[0,0,null]},{"id":21080,"nick":"\uc815\uc624","nationid":1,"level":25,"guild":"\uace0\ud55c\uc74d","guildid":13,"gpower":5,"gflag":64,"protection":0,"status":0,"conq":[0,0,null]}]}})

            get_list_url = '/game/api_fav.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

            html_source = get_html_response(get_list_url, 2)

            if html_source == '::ERROR::':

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[03]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1

            # 에러만 아니면 성공여부 상관없음!!

            next_ip = 'next'

            rand_timesleep()


        if next_ip == 'next':

            # 2. 친추 오랑캐 리스트 (좌표, 공격 횟수, 별수 추출) 

            # GET /game/api_fav.php?jsonpcallback=jsonp1334359483815&_=1334372336989&key=ac91d18916be985c476e6a4bbfb7bd56&act=getfavnpc&cat=2&_l=kr&_p=SG-IPHONE-KR HTTP/1.1

            # jsonp1334423982684({"code":0,"ret":{"favs":[[182038,258,27,1,0],[182039,253,26,1,0],[182040,239,19,1,0],[182041,121,17,1,0],[182042,46,21,1,0],[182044,248,9,1,0],[182045,67,11,1,0],[182046,41,13,1,0],[182400,164,95,1,0],[182401,146,87,1,0],[182402,147,77,1,0],[182403,206,83,1,0],[182404,159,68,1,0],[182405,159,67,1,0],[182406,193,68,1,0],[182407,176,69,1,2],[182408,138,55,1,0],[182409,135,47,1,0],[182410,206,39,1,0],[182411,152,32,1,0],[184781,173,44,1,0],[184782,206,44,1,0],[184783,279,47,1,0],[184784,180,42,1,0],[184786,268,37,1,0],[184787,257,40,1,0],[184788,211,30,1,0],[184789,194,35,1,0],[184790,238,33,1,0],[184791,170,27,1,0],[184792,167,25,1,0],[184795,265,27,1,0],[184796,257,22,1,0],[184797,166,5,1,0],[186088,164,115,1,0],[186089,62,119,1,0],[186090,57,119,1,0],[186091,4,124,1,0],[186092,114,116,1,1],[186093,104,111,1,0],[186094,91,112,1,0],[186095,221,106,1,0],[186096,219,105,1,0],[186097,265,109,1,0],[186098,191,110,1,0],[186099,234,108,1,0],[186100,227,106,1,0],[186101,78,104,1,1],[186102,65,110,1,0],[186103,27,106,1,0],[186104,199,101,1,0],[186105,276,100,1,0],[186106,272,101,1,0],[186107,256,102,1,0],[186108,251,97,1,0],[186109,102,102,1,0],[187815,152,203,1,0],[187816,131,200,1,0],[187817,27,209,1,0],[187818,163,201,1,0],[187819,213,198,1,0],[187820,117,198,1,0],[187821,109,201,1,0],[187822,34,199,1,0],[187823,19,203,1,0],[187824,136,196,1,0],[187825,198,196,1,0],[187826,181,191,1,0],[187827,172,195,1,0],[187828,243,196,1,0],[187829,166,195,1,0],[187830,220,192,1,0],[187831,261,194,1,0],[187832,197,190,1,0],[187833,143,187,1,0],[187834,91,195,1,0],[187835,73,196,1,0],[187836,181,183,1,0],[187837,198,186,1,0],[187838,43,193,1,0],[187839,39,190,1,0],[187840,277,188,1,0],[187841,120,189,1,0],[187842,64,187,1,0],[187843,68,186,1,0],[187844,163,181,1,0],[187845,165,180,1,0],[187846,10,187,1,0],[187847,212,179,1,0],[187848,139,176,1,0],[187849,212,178,1,0],[187850,194,180,1,0],[187851,233,177,1,0],[187852,122,180,1,0],[187853,110,182,1,0],[187854,86,179,1,0],[187855,85,177,1,0],[187856,34,177,1,0],[187857,161,175,1,0],[187858,212,174,1,0],[187859,20,177,1,0],[187860,17,176,1,0],[187861,13,177,1,0],[187862,188,170,1,0],[187863,257,173,1,0],[187864,251,171,1,0],[187866,166,79,1,0],[187867,193,61,1,0],[187868,250,38,1,0],[187871,264,135,4,0],[181998,137,31,1,3],[181999,126,30,1,3],[182000,147,28,1,3],[182001,120,34,1,3],[182036,246,26,1,3],[182037,59,31,1,3],[182043,276,10,1,3],[182047,275,1,1,3],[184785,178,40,1,3],[184793,268,30,1,3]]}})

            # [182038,258,27,1,0] ==> [오랑캐ID, X좌표, Y좌표, 별, 공격횟수]

            # 만약 findall 리스트 item수가 0이면 루프 탈출 후 return interval

            get_orang_xy_url = '/game/api_fav.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&act=getfavnpc&cat=2&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

            html_source = get_html_response(get_orang_xy_url, 2)

            if html_source == '::ERROR::':

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[04]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1

            if '"code":0' in html_source:

                find_orang_xy = re.findall('\[\d+,(\d+),(\d+),' + str(type_orang) + ',[0-2]', html_source)

                if find_orang_xy:

                    attack_x = find_orang_xy[0][0]

                    attack_y = find_orang_xy[0][1]

                    print('공격좌표 추출 완료 : ' + attack_x + '/' + attack_y)

                    next_ip = 'next'

                    rand_timesleep()

                else:

                    print('더이상 공격할 좌표가 없어 자동사냥 작업을 종료 합니다.')

                    next_ip = 'exit_auto_attack'

            else:

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[05]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1

        

        if next_ip == 'next':

            # 3. 공격좌표 이상유무 파악!!

            # GET /game/armament_action_do_api.php?jsonpcallback=jsonp1334359483816&_=1334372353885&key=ac91d18916be985c476e6a4bbfb7bd56&city=23764&act=anum&x=78&y=104&_l=kr&_p=SG-IPHONE-KR HTTP/1.1

            # jsonp1334424047624({"code":0,"ret":0})

            # "code":0,"ret":0 응답이 이거면 진행 아니면 다음루프 continue

            is_target_ok_url = '/game/armament_action_do_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + city_id + '&act=anum&x=' + attack_x + '&y=' + attack_y + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

            #print('is_target_ok_url :' + is_target_ok_url)

            html_source = get_html_response(is_target_ok_url, 2)

            if html_source == '::ERROR::':

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[06]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1

            if '"code":0' in html_source:

                next_ip = 'next'

                print('좌표[' + attack_x + '/' + attack_y + '] 공격가능!!')

                rand_timesleep()

            else:

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[08]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1


        if next_ip == 'next':

            # 4. 병력 정보

            # GET /game/soldier_educate_api.php?jsonpcallback=jsonp1334359483817&_=1334372353891&key=ac91d18916be985c476e6a4bbfb7bd56&city=23764&_l=kr&_p=SG-IPHONE-KR HTTP/1.1

            # jsonp1334424148283({"code":0,"ret":{"soldiers":[[1,0,1],[2,110,1],[3,0,1],[4,0,1],[5,0,1],[6,0,1],[7,0,1],[8,0,1],[9,0,0],[10,0,1],[11,500,1],[12,0,0],[13,0,1],[14,0,0],[15,4500,1]],"space":5390,"head":7103,"def":1,"next":[16,22],"f":107896}})

            # type_soldier가 num_soldier만큼 있으면 통과 없으면 5, 6, 7, 8 스킵후 interval 만큼 대기!! type_soldier, num_soldier

            get_soldier_num_url = '/game/soldier_educate_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + city_id + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

            html_source = get_html_response(get_soldier_num_url, 2)

            if html_source == '::ERROR::':

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[09]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1

            if '"code":0' in html_source:

                find_soldier_num = re.findall('\['+ str(type_soldier) + ',(\d+),[01]\]', html_source)

                if find_soldier_num:

                    my_soldier_num = find_soldier_num[0]

                    

                    if int(my_soldier_num) >= int(num_soldier):

                        # 병력이 충분하면.. 통과

                        print('병력 보유[' + str(my_soldier_num) + '] 공격 진행!!')

                        next_ip = 'next'

                        rand_timesleep()

                    else:

                        # 병력이 적으면!! 인터벌 대기

                        print('더이상 공격할 병력이 없어 다음 인터벌 까지 대기합니다.')

                        next_ip = 'wait_interval'

                        rand_timesleep()

                else:

                    print('더이상 공격할 병력이 없어 다음 인터벌 까지 대기합니다.')

                    next_ip = 'wait_interval'

                    rand_timesleep()

            else:

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[10]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1

        

        if next_ip == 'next':

            # 5. 통솔 장수 선택

            # GET /game/gen_conscribe_api.php?jsonpcallback=jsonp1334359483818&_=1334372360888&key=ac91d18916be985c476e6a4bbfb7bd56&city=23764&action=gen_list&extra=1&_l=kr&_p=SG-IPHONE-KR HTTP/1.1

            # jsonp1334424202909({"code":0,"ret":{"hero":[{"id":89862,"gid":189,"p":33,"i":41,"c1":18,"f":80,"g":13,"c2":900,"fy":0,"s":0,"e":16,"w":1,"tw":8,"tl":31,"ex":118887,"te":565620,"np":0,"ni":0,"nc1":0,"nc2":250,"ns":0,"ncd":0,"pr":39000},{"id":93364,"gid":179,"p":30,"i":55,"c1":16,"f":75,"g":13,"c2":823,"fy":0,"s":0,"e":16,"w":0,"tw":8,"tl":17,"ex":10843,"te":565620,"np":0,"ni":0,"nc1":0,"nc2":180,"ns":0,"ncd":0,"pr":39000},{"id":96018,"gid":207,"p":59,"i":12,"c1":33,"f":75,"g":13,"c2":830,"fy":0,"s":0,"e":16,"w":1,"tw":7,"tl":26,"ex":291604,"te":565620,"np":0,"ni":0,"nc1":0,"nc2":180,"ns":0,"ncd":0,"pr":39000},{"id":97215,"gid":177,"p":31,"i":49,"c1":29,"f":73,"g":13,"c2":845,"fy":0,"s":0,"e":16,"w":0,"tw":7,"tl":29,"ex":31237,"te":565620,"np":0,"ni":0,"nc1":0,"nc2":180,"ns":0,"ncd":0,"pr":39000},{"id":97340,"gid":186,"p":32,"i":43,"c1":19,"f":75,"g":13,"c2":844,"fy":0,"s":0,"e":16,"w":1,"tw":2,"tl":23,"ex":3042,"te":565620,"np":8,"ni":15,"nc1":11,"nc2":419,"ns":0,"ncd":0,"pr":39000},{"id":98342,"gid":126,"p":33,"i":53,"c1":26,"f":30,"g":12,"c2":879,"fy":0,"s":0,"e":16,"w":0,"tw":18,"tl":27,"ex":221902,"te":257100,"np":15,"ni":45,"nc1":19,"nc2":759,"ns":0,"ncd":0,"pr":36000},{"id":104287,"gid":185,"p":11,"i":42,"c1":13,"f":60,"g":12,"c2":617,"fy":0,"s":0,"e":16,"w":0,"tw":0,"tl":3,"ex":99753,"te":257100,"np":0,"ni":0,"nc1":0,"nc2":0,"ns":0,"ncd":0,"pr":36000},{"id":109341,"gid":73,"p":44,"i":54,"c1":32,"f":15,"g":15,"c2":830,"fy":0,"s":0,"e":16,"w":2,"tw":2,"tl":10,"ex":241832,"te":2737601,"np":0,"ni":0,"nc1":0,"nc2":30,"ns":0,"ncd":0,"pr":45000},{"id":111918,"gid":45,"p":37,"i":54,"c1":26,"f":55,"g":10,"c2":854,"fy":0,"s":0,"e":16,"w":0,"tw":0,"tl":0,"ex":26823,"te":53119,"np":0,"ni":0,"nc1":0,"nc2":180,"ns":0,"ncd":0,"pr":30000}]}})

            # jsonp1334705981745({"code":0,"ret":{"hero":[{"id":89862,"gid":189,"p":33,"i":41,"c1":18,"f":85,"g":13,"c2":910,"fy":0,"s":0,"e":16,"w":0,"tw":10,"tl":32,"ex":443066,"te":565620,"np":0,"ni":0,"nc1":0,"nc2":260,"ns":0,"ncd":0,"pr":39000},{"id":93364,"gid":179,"p":30,"i":55,"c1":16,"f":75,"g":13,"c2":823,"fy":0,"s":0,"e":16,"w":1,"tw":9,"tl":17,"ex":332048,"te":565620,"np":0,"ni":0,"nc1":0,"nc2":180,"ns":0,"ncd":0,"pr":39000},{"id":96018,"gid":207,"p":62,"i":12,"c1":33,"f":75,"g":14,"c2":868,"fy":0,"s":0,"e":16,"w":1,"tw":7,"tl":26,"ex":47550,"te":1244364,"np":0,"ni":0,"nc1":0,"nc2":180,"ns":0,"ncd":0,"pr":42000},{"id":97215,"gid":177,"p":31,"i":49,"c1":29,"f":73,"g":13,"c2":845,"fy":0,"s":0,"e":16,"w":0,"tw":8,"tl":31,"ex":352312,"te":565620,"np":0,"ni":0,"nc1":0,"nc2":180,"ns":0,"ncd":0,"pr":39000},{"id":97340,"gid":186,"p":32,"i":43,"c1":19,"f":75,"g":13,"c2":844,"fy":0,"s":0,"e":16,"w":2,"tw":3,"tl":23,"ex":323906,"te":565620,"np":8,"ni":15,"nc1":11,"nc2":419,"ns":0,"ncd":0,"pr":39000},{"id":98342,"gid":126,"p":33,"i":57,"c1":26,"f":35,"g":13,"c2":917,"fy":0,"s":0,"e":16,"w":4,"tw":22,"tl":27,"ex":284646,"te":565620,"np":15,"ni":45,"nc1":19,"nc2":759,"ns":0,"ncd":0,"pr":39000},{"id":104287,"gid":185,"p":11,"i":45,"c1":13,"f":60,"g":13,"c2":653,"fy":0,"s":0,"e":16,"w":0,"tw":0,"tl":4,"ex":162018,"te":565620,"np":0,"ni":0,"nc1":0,"nc2":0,"ns":0,"ncd":0,"pr":39000},{"id":109341,"gid":73,"p":44,"i":54,"c1":32,"f":20,"g":15,"c2":950,"fy":0,"s":0,"e":16,"w":0,"tw":2,"tl":12,"ex":561262,"te":2737601,"np":0,"ni":0,"nc1":0,"nc2":150,"ns":0,"ncd":0,"pr":45000}]}})

            # 만약 findall 리스트 item수가 0이면 10번으로

            # 리스트 item은 있으나 c2(통솔력)가 딸리는 장수들 뿐이면 역시 10번으로

            # 리스트item은 있으나  e(기력)이 딸리는 장수들 뿐이면 역시 10번으로

            

            get_gen_id_url = '/game/gen_conscribe_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + city_id + '&action=gen_list&extra=1&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

            html_source = get_html_response(get_gen_id_url, 2)

            if html_source == '::ERROR::':

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[11]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1

            if '"code":0' in html_source:

                #find_gen_id = re.findall('"gid":(\d+),"p":\d+,"i":\d+,"c1":\d+,"f":\d+,"g":\d+,"c2":([' + str(num_soldier)[0] + '-9]\d*),', html_source)

                find_gen_id = re.findall('"gid":(\d+),"p":\d+,"i":\d+,"c1":\d+,"f":\d+,"g":\d+,"c2":(\d+),', html_source)

                selected_gen_id = ''

                if find_gen_id:

                    for loop_idx in find_gen_id:

                        if int(loop_idx[1]) >=  num_soldier:

                            selected_gen_id = loop_idx[0]

                            break

                        else:

                            selected_gen_id = ''

                    

                    if selected_gen_id != '':

                        print('통솔 장수 ID 추출 완료[' + str(selected_gen_id) + '] 공격 진행!!')

                        next_ip = 'next'

                        rand_timesleep()

                    else:

                        print('더이상 공격할 장수가 없어 다음 인터벌 까지 대기합니다.')

                        next_ip = 'wait_interval'

                        rand_timesleep()

                else:

                    print('더이상 공격할 장수가 없어 다음 인터벌 까지 대기합니다.')

                    next_ip = 'wait_interval'

                    rand_timesleep()

            else:

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[12]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1


        if next_ip == 'next':

            # 6. 공격정보 상세

            # GET /game/armament_action_do_api.php?jsonpcallback=jsonp1334359483819&_=1334372374733&key=ac91d18916be985c476e6a4bbfb7bd56&city=23764&action=do_war&attack_type=7&gen=189&area=78&area_x=104&soldier_num15=500&_l=kr&_p=SG-IPHONE-KR HTTP/1.1

            # jsonp1334424277458({"code":0,"ret":{"carry":396000,"cost_food":90000,"cost_wood":0,"cost_iron":0,"cost_gold":0,"distance":20160,"travel_sec":540}})

            # 음식소요와 공격명령 파라메터 생성!!

            # 타음 인터벌 맥스값 계산 세트!! 공식 : (travel_sec + 60 * 2)가  inteval_sec보다 크면 inteval_sec 교체

            attack_info_url = '/game/armament_action_do_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + city_id + '&action=do_war&attack_type=7&gen=' + selected_gen_id + '&area=' + attack_x + '&area_x=' + attack_y + '&soldier_num' + str(type_soldier) + '=' + str(num_soldier) + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

            html_source = get_html_response(attack_info_url, 2)

            if html_source == '::ERROR::':

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[13]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1

            if '"code":0' in html_source:

                attack_info = re.search('"carry":(\d+),"cost_food":(\d+),"cost_wood":(\d+),"cost_iron":(\d+),"cost_gold":(\d+),"distance":(\d+),"travel_sec":(\d+)',html_source).group()

                attack_info = '&' + attack_info.replace('"', '').replace(':', '=').replace(',', '&')

                food_per_attack     = int(re.search('cost_food":(\d+),', html_source).group(1))

                interval_per_attack = int(re.search('travel_sec":(\d+)}', html_source).group(1)) * 2

                print('도시보유 식량 : ' + city_tot_food + ', 공격소요 식량 : ' + str(food_per_attack))

                print('공격소요시간(복귀시간포함) : ' + str(interval_per_attack))


                if int(city_tot_food) < int(food_per_attack):

                    # 식량교환(1골드당 7.6923 식량)

                    need_chg_tot_gold = int(food_per_attack / 7.6923)

                    # 계산된 골드 보다 10골드 더 교환 요건 걍 내맴

                    need_chg_tot_gold += 100

                    # 현재 도시의 돈이 need_chg_tot_gold보다 적으면 진행 불가 인터벌 대기!!

                    if city_tot_money < need_chg_tot_gold:

                        print('도시에 다음 전투 식량 교환을 위한 동전이 부족하여 다음 인터벌 까지 대기합니다.')

                        next_ip = 'wait_interval'

                        rand_timesleep()

                    else:

                        ret_do_g2f = do_g2f(need_chg_tot_gold, city_id)

                        if ret_do_g2f == '::ERROR::':

                            print('식량자원 교환에 실패하여 자동사냥을 중지합니다!!')

                            next_ip = 'exit_auto_attack'

                        else:

                            rand_timesleep()

                            print('식량자원 교환 성공!! 공격 진행!!')

                            next_ip = 'next'

                else:

                    next_ip = 'next'

                    print('식량자원 요건 충족!! 공격 진행!!')

                    rand_timesleep()

            else:

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[14]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1


        if next_ip == 'next':

            # 7. 도시자원 정보(의미 없음)

            # GET /game/get_cityinfo_api.php?jsonpcallback=jsonp1334359484911&_=1334372387271&key=ac91d18916be985c476e6a4bbfb7bd56&city=23764&_l=kr&_p=SG-IPHONE-KR HTTP/1.1

            # jsonp1334424402425({"code":0,"ret":{"city":[27,183,764129,159000,1276893,159000,1214668,159000,1980380,159000,6656,8125,10,12,11,26,17,21,19,19,1,4,14,[{"id":52066,"itemid":166,"secs":502596},{"id":52201,"itemid":126,"secs":14202}],0],"grade":43,"money":100}})

            get_city_info_url = '/game/get_cityinfo_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + city_id + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

            html_source = get_html_response(get_city_info_url, 2)

            if html_source == '::ERROR::':

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[15]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1

            if '"code":0' in html_source:

                next_ip = 'next'

                rand_timesleep()

            else:

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[16]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1


        if next_ip == 'next':        

            # 8. 공격명령!!

            # GET /game/armament_action_task_api.php?jsonpcallback=jsonp1334359483820&_=1334372411619&key=ac91d18916be985c476e6a4bbfb7bd56&city=23764&action=war_task&attack_type=7&gen=189&area=78&area_x=104&soldier_num15=500&_l=kr&_p=SG-IPHONE-KR&carry=396000&cost_food=90000&cost_wood=0&cost_iron=0&cost_gold=0&distance=7440&travel_sec=180 HTTP/1.1

            # jsonp1334424477066({"code":0,"ret":{"cd":[{"id":6334289,"cdtype":4,"target":7,"owner":189,"secs":540,"ret":0,"ext":"166\/79"}]}})

            do_attack_url = '/game/armament_action_task_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + city_id + '&action=war_task&attack_type=7&gen=' + selected_gen_id + '&area=' + attack_x + '&area_x=' + attack_y + '&soldier_num' + str(type_soldier) + '=' + str(num_soldier) + '&_l=kr&_p=SG-IPHONE-KR' + attack_info + '{}HTTP/1.1'.format(urllib.parse.quote(' '))

            html_source = get_html_response(do_attack_url, 2)

            if html_source == '::ERROR::':

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[15]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1

            if '"code":0' in html_source:

                print('좌표[' + attack_x + '/' + attack_y + '] 공격완료!!')

                # 에러카운트 초기화

                err_cnt = 0

                # 롱텀 인터벌 판별 및 스왑

                if interval_per_attack > inteval_sec:

                    print('현재 인터벌[' + str(inteval_sec) + ']보다 큰 인터벌[' + str(interval_per_attack) + ']발견!! 스왑인터벌')

                    inteval_sec = interval_per_attack

                # 식량교환(1골드당 7.6923 식량)

                need_chg_tot_gold = int(food_per_attack / 7.6923)

                # 계산된 골드 보다 10골드 더 교환 요건 걍 내맴

                need_chg_tot_gold += 100

                

                # 현재 도시의 돈이 need_chg_tot_gold보다 적으면 진행 불가 인터벌 대기!!

                if int(city_tot_money) < int(need_chg_tot_gold):

                    print('도시에 다음 전투 식량 교환을 위한 동전이 부족하여 다음 인터벌 까지 대기합니다.')

                    next_ip = 'wait_interval'

                    rand_timesleep()

                else:

                    ret_do_g2f = do_g2f(need_chg_tot_gold, city_id)

                    if ret_do_g2f == '::ERROR::':

                        print('식량자원 교환에 실패하여 자동사냥을 중지합니다!!')

                        next_ip = 'exit_auto_attack'

                    else:

                        rand_timesleep()

                        print('소비 식량자원 보충 성공!!')

                        next_ip = 'next'

            else:

                if err_cnt <= 3:

                    err_cnt += 1

                    print('[16]Error발생')

                    timesleep(5)

                    continue

                else:

                    print('3회 이상 에러가 발생하여 자동 사냥을 중단합니다!!')

                    return -1

                

        # 10. 1번으로 반복

        if next_ip == 'next':

            continue

        

        # 11. 도시 사냥 종료 인터벌 대기!!

        if next_ip == 'wait_interval':

            return inteval_sec

        

        # 12. 사냥불가로 인한 사냥 종료(해당 도시는 더이상 공격 안함 리스트에서 팝시킴)

        if next_ip == 'exit_auto_attack':

            return -1


def get_time():

    return str(int(time.time() * 1000))


def rand_timesleep():

    rand_sec = random.randrange(1,2)

    #print('오토검출 방지 대기 : ' + str(rand_sec) + '초')

    time.sleep(rand_sec)

    return


def timesleep(interval_sec):

    print('대기명령 : ' + str(interval_sec) + '초...')

    time.sleep(interval_sec)

    return


def make_cookie():

    gen_cookie = ''

    for l_idx in range(0,32):

        rand_num = random.randrange(1,1000)

        if rand_num > 500:

            gen_cookie += chr(random.randrange(97, 102))

        else:

            gen_cookie += chr(random.randrange(48, 57))

    

    return gen_cookie


def get_html_response(send_url, attempt_type, decode_type = 'utf-8'):

    err_cnt = 0

    

    while True:

        try:

            if attempt_type == 1:

                # 메인 호스트 호출

                conn = http.client.HTTPConnection('m.tapsg.com', 80)

            elif attempt_type == 2:

                # 사용자 서버 호스트 호출

                conn = http.client.HTTPConnection(base_user_host, 80)

            elif attempt_type == 3:

                conn = http.client.HTTPConnection('129.100.170.100', 8181)

            conn.putrequest('GET', send_url)

            

            if attempt_type == 1:

                # 메인 호스트 호출

                conn.putheader('Host','m.tapsg.com')

                conn.putheader('User-Agent','{}/1.10 CFNetwork/548.0.4 Darwin/11.0.0'.format(urllib.parse.quote('손바닥 삼국지')))        

            elif attempt_type == 2:

                # ID종속 서버 호스트 호출

                conn.putheader('Host',base_user_host)

                conn.putheader('User-Agent','Mozilla/5.0 (iPhone; CPU iPhone OS 5_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9A405')

            elif attempt_type == 3:

                conn.putheader('Host','129.100.170.100:8181')

                conn.putheader('User-Agent','Mozilla/5.0 (iPhone; CPU iPhone OS 5_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9A405')

            conn.putheader('Accept','*/*')

            conn.putheader('Accept-Language','ko-kr')

            conn.putheader('Accept-Encoding','gzip, deflate')

            conn.putheader('Cookie','phpbb3_surfz_k=; phpbb3_surfz_sid=' + base_cookie + '; phpbb3_surfz_u=1')

            conn.putheader('Connection','keep-alive')

            conn.putheader('','')

            conn.endheaders()

            resp = conn.getresponse()

            if str(resp.status).strip() != '200':

                if attempt_type == 3:

                    print('허가되지 않은 장소에서의실행 요청입니다!!')

                    sys.exit()

                print(str(send_url) + ' 페이지에 접속하는데에 실패하였습니다.')

                conn.close()

                resp.close()        

                return '::ERROR::'

            else:

                ret_html_bytes = resp.read()

                ret_html_str = str(ret_html_bytes.decode(decode_type))

                conn.close()

                resp.close()

                return ret_html_str

        except Exception:

            if attempt_type == 3:

                print('허용되지 않은 장소에서의 실행입니다!! 프로그램을 종료합니다!!')

                sys.exit()

            if err_cnt <= 3:

                print('서버연결 응답없음!! 재시도[' + str(err_cnt) + '회')

                err_cnt += 1

                timesleep(30)

                continue

            else:

                print('손바닥 삼국지 서버로 부터 응답이 없습니다. 프로그램 종료!!')

                sys.exit()


def attempt_login():

    print('Payment 체크..')

    payment_chk_url = '/dopayment.php?user=&act=query{}HTTP/1.1'.format(urllib.parse.quote(' '))

    html_source = get_html_response(payment_chk_url, 1)

    if html_source != '::ERROR::':

        print('성공')

    else:

        print('손바닥 삼국지 서버 접속에 실패하였습니다!!\n잠시후 다시 시도하여주세요!!')

        return '::ERROR::'

    

    del(payment_chk_url)

    return 0


def do_g2f(gold_value, city_id):

    # 교환실행

    do_g2f_url = '/game/local_market_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + city_id + '&reso_put=giveput&g2f=' + str(gold_value) + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

    html_source = get_html_response(do_g2f_url, 2)

    if html_source == '::ERROR::':

        return '::ERROR::'

    if '"code":0' in html_source:

        print('[' + str(gold_value) + ']동전을 [' + str(int(gold_value * 7.6923)) + ']식량으로 교환 하는데 성공 하였습니다!!')

        return 'OK'

    else:

        print('동전 ==> 식량 교환에 실패하였습니다!!')

        print('Error Code : ' + html_source)

        return '::ERROR::'

    

def get_soldier(city_id, soldier_type):

    # 병영정보

    soldier_url = '/game/soldier_educate_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + city_id + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

    html_source = get_html_response(soldier_url, 2)

    if html_source == '::ERROR::':

        return '::ERROR::'


    if '"code":0' in html_source:

        soldier_num = re.findall('\[' + str(soldier_type) + ',(\d+),\d+\]', html_source)

        if soldier_num:

            soldier_num = int(soldier_num[0])

        else:

            soldier_num = 0

            

        return soldier_num

    else:

        print('사용자 병력 정보 추출에 실패하였습니다!!')

        print('Error Code : ' + html_source)

        return -1


def do_scout(point_x, point_y):

    # 척후병 보유 여부 판단!!

    soldier_num = get_soldier(base_city_id, '2')

    if soldier_num > 0:

        print('척후병 보유수 : ' + str(soldier_num))

    elif soldier_num == 0:

        print('척후병 보유병사가 없으므로 정찰을 진행하지 않습니다!!')

        return 'SKIP'

    else:

        print('척후병 보유수를 가져오는데 실패하였습니다!!')

        return '::ERROR::'

    rand_timesleep()

    

    # 정찰사전정보 수집

    # 본진으로 부터 해당 좌표까지의 거리, 소요자원, 시간, 해당좌표의 ID값 추출 

    scout_info_url = '/game/armament_action_do_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + base_city_id + '&action=do_war&attack_type=3&tai_num=1&area=' + str(point_x) + '&area_x=' + str(point_y) + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

    html_source = get_html_response(scout_info_url, 2)

    if html_source == '::ERROR::':

        return '::ERROR::'

    if '"code":0' in html_source:

        scout_info = re.search('"carry":(\d+),"cost_food":(\d+),"cost_wood":(\d+),"cost_iron":(\d+),"cost_gold":(\d+),"distance":(\d+),"travel_sec":(\d+)',html_source).group()

        scout_info = '&' + scout_info.replace('"', '').replace(':', '=').replace(',', '&')

        cost_food = re.search('cost_food":(\d+),', html_source).group(1)

        print('정찰소요 식량 : ' + str(cost_food))

    else:

        print('정찰지[' + point_x + '/' + point_y + '] 정찰사전정보 수집실패!!')

        print('Error Code : ' + html_source)

        return '::ERROR::'

    rand_timesleep()

    

    # 도시정보 호출 후 식량자원량 추출

    city_resource = get_city_resource(base_city_id)

    if city_resource:

        if city_resource == '::ERROR::':

            return '::ERROR::'

        else:

            city_food = city_resource[0][1]

    else:

        return '::ERROR::'

    rand_timesleep()

    

    # 충분한 식량이 있는지 판단!!

    if int(cost_food) > int(city_food):

        # 없으면 스킵!!

        return '::ERROR::'


    # 정찰

    scout_url = '/game/armament_action_task_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + base_city_id + '&action=war_task&attack_type=3&tai_num=1&area=' + str(point_x) + '&area_x=' + str(point_y) + '&_l=kr&_p=SG-IPHONE-KR' + scout_info + '{}HTTP/1.1'.format(urllib.parse.quote(' '))

    html_source = get_html_response(scout_url, 2)

    if html_source == '::ERROR::':

        return '::ERROR::'

    if '"code":0' in html_source:

        target_id = re.search('"id":(\d+),"cdtype"', html_source).group(1)

        print('정찰지[' + point_x + '/' + point_y + '] ID : ' + target_id + ' : 정찰시도 성공!!')

        return 'OK'

    else:

        print('정찰지[' + point_x + '/' + point_y + '] ID : ' + target_id + ' : 정찰시도 실패!!')

        print('Error Code : ' + html_source)

        return '::ERROR::'

    rand_timesleep()


def get_city_resource(city_id):

    # 도시정보  

    cityinfo_url = '/game/get_cityinfo_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + city_id + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

    html_source = get_html_response(cityinfo_url, 2)

    if html_source == '::ERROR::':

        return '::ERROR::'

    if '"code":0' in html_source:

        city_rs = re.findall('city":\[\d+,\d+,(\d+),\d+,(\d+),\d+,(\d+),\d+,(\d+),', html_source)

        print('동전 : ' + city_rs[0][0] + ', 식량 : ' + city_rs[0][1] + ', 목재 : ' + city_rs[0][2] + ', 철광석 : ' + city_rs[0][3])

        return city_rs

    else:

        print('사용자 정보 추출에 실패하였습니다!!')

        print('Error Code : ' + html_source)

        return '::ERROR::'


def scan_area_all(max_findout_cnt,orangke_type, input_point_x, input_point_y):

        #====지역스캔

        findout_cnt = 1

        err_cnt = 0

        recp_orang = re.compile('\[(\d+),(\d+),([' + str(orangke_type) + ']{1}),\[(\d+)]]')

        recp_food  = re.compile('\[(\d+),(\d+),103,\[(\d+),(\d+),"",""\]\]')

        # 이전 스캔데이터들이 존재하면 파일명을 변경해 백업한다.

        if os.access('orang_data.dat', os.F_OK):

            os.rename('orang_data.dat', 'old_orang_data' + str(time.strftime('%y%m%d%H%M%S')) + '.dat')

        if os.access('food_data.dat', os.F_OK):

            os.rename('food_data.dat', 'old_food_data' + str(time.strftime('%y%m%d%H%M%S')) + '.dat')

        f_orang = open('orang_data.dat', 'w')

        f_food  = open('food_data.dat', 'w')

        for point_y in range(input_point_y, 278, 7):

                for point_x in range(input_point_x, 278, 7):

                        detail_url = '/game/api_world_map.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&x=' + str(point_x) + '&y=' + str(point_y) + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

                        token_str = get_html_response(detail_url, 2)

                        rand_timesleep()

                        if token_str == '::ERROR::':

                            return '::ERROR::'

                        if findout_cnt <= max_findout_cnt:

                            if '"code":0' not in token_str:

                                    print('[지도스캔좌표 : ' + str(point_x) + '/' + str(point_y) + ']의 스캔에 실패하였습니다.\r\n이 지역을 제외하고 다음지역을 스캔합니다!!')

                                    if err_cnt > 3:

                                            return '::ERROR::'

                                    else:

                                            err_cnt += 1

                            else:

                                    # 오랑캐 스캔!!

                                    find_orang_x_y = recp_orang.findall(token_str)

                                    for idx_x_y in find_orang_x_y:

                                        if idx_x_y:

                                            print(list(idx_x_y), end = '')

                                            print(' ' + list(idx_x_y)[0] + '/' + list(idx_x_y)[1] + ' : 오랑캐 좌표 발견!!')

                                            # 정찰 시도!!

                                            ret_scout = do_scout(list(idx_x_y)[0], list(idx_x_y)[1])

                                            if ret_scout == 'OK':

                                                f_orang.write('[' + list(idx_x_y)[0] + ',' + list(idx_x_y)[1] + ',정찰시도성공]\n')

                                            else:

                                                f_orang.write('[' + list(idx_x_y)[0] + ',' + list(idx_x_y)[1] + ',정찰시도실패]\n')


                                            findout_cnt += 1

                                    # 식량창고(대) 스캔!!

                                    find_food_x_y = recp_food.findall(token_str)

                                    for idx_x_y in find_food_x_y:

                                        if idx_x_y:

                                            print(list(idx_x_y), end = '')

                                            print(' 미점령 식량창고(대) 좌표 발견!!')

                                            f_food.write(str(idx_x_y) + '\n')

                        else:

                            print('찾은 오랑캐 좌표수 : ' + str(findout_cnt-1) + ', 제한 오랑캐 좌표수 : ' + str(max_findout_cnt) + '\r\n사용자 탐색 제한값에 도달하여 탐색을 중지합니다!!')

                            print('찾아진 오랑캐 좌표가 ''orang_dat.dat''파일로 저장되었습니다!')

                            return '0'

        return '0'

        print('찾아진 오랑캐 좌표가 ''orang_dat.dat''파일로 저장되었습니다!')

        f_orang.close()

        f_food.close()


def get_enemy_info_from_file():

    # 파일오픈..

    try:

        f_new = open('orang_final.dat', 'w')

    except Exception:

        print('오랑캐 좌표 분석을 위한 파일을 여는데 실패하였습니다!!')

        return '::ERROR::'

    

    try:

        # 편지함 뒤지기(의미 없음!!) 

        # 로그패턴을 최대한 실제 어플과 비슷하게 하여 오토 검출을 방해하기 위함

        # (해봐야 맘먹고 찾으면 다 걸리겠지만 ㅋㅋ)

        viewmail_url = '/game/message_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&page=1&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

        html_source = get_html_response(viewmail_url, 2)

        if html_source == '::ERROR::':

            return '::ERROR::'

        if '"code":0' in html_source:

            pass

        else:

            print('정찰 정보를 추출 하는데 실패하였습니다.')

            print('viewmail_url : ' + html_source)

            return '::ERROR::'

        rand_timesleep()

        

        # 정찰결과 리스팅

        scout_info_dat = ''

        while True:

            scout_list_url = '/game/war_result_list_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&page=1&type=3&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

            html_source = get_html_response(scout_list_url, 2)

            if html_source == '::ERROR::':

                return '::ERROR::'

            rand_timesleep()

            if '"code":0' in html_source:

                scout_info_dat = html_source

                # 현재 추출되어진 ID들을 결과함에서 삭제함.. 페이지가 10page 맥스이고 뒤로 밀려 어쩔수 없음..

                scout_del_id = re.findall('"id":(\d+),', html_source)

                

                # 편지함에 저장된 정찰정보의 해당 좌표(정찰이 성공한 좌표만)별 ID값 추출

                if len(scout_del_id):

                    # 제대로 검출 되면!!

                    for list_item in scout_del_id:

                        print('검출된 ID : ' + list_item)

                        point_x = re.search('{"id":' + list_item + ',.+?"dx":(\d+),"dy":(\d+),', scout_info_dat).group(1)

                        point_y = re.search('{"id":' + list_item + ',.+?"dx":(\d+),"dy":(\d+),', scout_info_dat).group(2)

                        print('point_x : ' + point_x + ', point_y : ' + point_y)

                        scout_detail_url = '/game/war_result_info_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&id=' + str(list_item) + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

                        html_source = get_html_response(scout_detail_url, 2)

                        if html_source == '::ERROR::':

                            return '::ERROR::'

                        if '"code":0' in html_source:

                            str_token = str(html_source)

                            if '\\uc0b0\\ub3c4\\uc801' in str_token:

                                san_num = '1'

                            else:

                                san_num = '0'

                            if '\\ud654\\uc801' in str_token:

                                hwa_num = '1'

                            else:

                                hwa_num = '0'

                            write_str = '[' + point_x + ',' + point_y + ',' + '산도적(' + san_num + '),화적(' + hwa_num + ')]' 

                            print(write_str)

                            f_new.write(write_str + '\n')

                            rand_timesleep()

                            if int(hwa_num) == 0 and int(san_num) > 0:

                                add_friend_url = '/game/api_fav.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&act=addreport&wid=' + str(list_item) + '&cat=2&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

                                html_source = get_html_response(add_friend_url, 2)

                                if html_source == '::ERROR::':

                                    return '::ERROR::'

                                if '"code":0' in html_source:

                                    print(write_str + 'Only 산도적 오랑캐 ==> 친구추가완료!!')

                                else:

                                    print(write_str + 'Only 산도적 오랑캐 ==> 친구추가실패!!')

                                    print('add_friend_url : ' + html_source)

                                rand_timesleep()

                        else:

                            print('scout_detail_url Error : ' + html_source)

                else:

                    print('[' + point_x + '/' + point_y + '] 병력상세정보 검출 실패!!')

                    print('scout_detail_url : ' + scout_detail_url)


                if len(scout_del_id):

                    del_str = ''

                    del_id_cnt = len(scout_del_id)

                    while len(scout_del_id):

                        del_pop_item = str(scout_del_id.pop())

                        if len(scout_del_id) == 0:

                            del_str += del_pop_item

                        else:

                            del_str += del_pop_item + '%2C'

                    scout_del_url = '/game/war_result_list_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&action=delete&id=' + del_str + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

                    #print('scout_del_url : ' + scout_del_url)

                    html_source = get_html_response(scout_del_url, 2)

                    if html_source == '::ERROR::':

                        return '::ERROR::'

                    rand_timesleep()

                    if '"code":0' in html_source:

                        print('정찰완료 정보' + str(del_id_cnt) + '개 삭제 완료!!')

                    else:

                        print('정찰완료 정보' + str(del_id_cnt) + '개 삭제 실패!!')

                        print('scout_del_url : ' + scout_del_url)

                    print('다음 정찰결과 정보 추출..')

                else:

                    print('모든 정찰결과 정보 추출 완료!!')

                    break

            else:

                print('정찰결과 리스트를 불러오는데 실패하였습니다. 프로그램을 종료합니다!!')

                print('Error Code : ' + html_source)

                return '::ERROR::'


    finally:

        print('정찰결과 분석 정보가 ''orang_final.dat''에 저장되었습니다!!')

        f_new.close()


# 메인함수 시작!!


# 장소 인증

chk_auth()


print("""

***************************************************************

손바닥삼국지 도우미 Ver 0.31(alpha) - by hElLoOnG(2012.04.02)

***************************************************************

*주의사항

*이 프로그램 사용으로 인하여 발생하는 불이익에 대하여

*개발자는 어떠한 책임도 지지 않습니다.

*

*기타 문의 및 버그 수정 요청은 살포시 넣어둬 주세요 ㅋㅋ 

***************************************************************

""")


# 쿠키 생성

base_cookie = make_cookie()

print('Session 생성 : ' + base_cookie)


# 사용자 아이디/패스워드 입력부(입력안하면 기본 아이디로 진행)

temp_user_id = input('손바닥삼국지 ID : ')

if str(temp_user_id).strip() != '':

    base_user_id = temp_user_id

    print('입력된 사용자 ID : ' + base_user_id)

else:

    print('ID가 입력되지 않았습니다!!')

    sys.exit()

temp_user_pw = input('손바닥삼국지 PW : ')

if str(temp_user_pw).strip() != '':

    base_user_pw = temp_user_pw

    print('입력된 사용자 PW : ' + base_user_pw)

else:

    print('PW가 입력되지 않았습니다!!')

    sys.exit()


# 실제 앱에서 일어나는 의미없는 체크

print('손바닥 삼국지 서버로 접속을 시도합니다...')

html_source = attempt_login()

if html_source == '::ERROR::':

    sys.exit()


rand_timesleep()

    

# 사용자 서버 정보 추출

print('사용자의 손바닥 삼국지 서버 정보를 추출합니다...')

get_server_url =  '/info.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&user=' + base_user_id + '&action=login&pvp=0&code=a1c1ef3363ae6f52d8e823ecd7d62da618a98c43&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

html_source = get_html_response(get_server_url, 1)

if html_source == '::ERROR::':

    sys.exit()

if '"code":0' in html_source:

    base_user_host = re.search('k(\d+)\.tapsg\.com', html_source).group()

    print('사용자 서버 추출 성공 : ' + base_user_host)

else:

    print('사용자 서버정보 추출에 실패하였습니다!!\nID, PW를 확인하고 다시 시도하여 주세요!!')

    print('Error Code : ' + html_source)

    sys.exit()


# 실제 인증 키값 추출

print('손바닥 삼국지 인증키 값을 추출합니다...')

login_url = '/game/login_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&username=' + base_user_id + '&password=' + base_user_pw + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

print('login_url : ' + login_url)

html_source = get_html_response(login_url, 2)

if html_source == '::ERROR::':

    sys.exit()

if '"code":0' in html_source:

    base_token = re.search('key":"(\\w+)"}',html_source).group(1)

    print('사용자 인증키 추출 성공 : ' + base_token)

else:

    print('사용자 인증키 추출에 실패하였습니다!!')

    print('Error Code : ' + html_source)

    sys.exit()


# 사용자 정보 추출

#userinfo_url : jsonp1333982142599({"code":0,"ret":{"user":{"id":20440,"nick":"helloong","nationid":1,"level":39,"money":100,"guild":"\uace0\ud55c\uc74d","guildid":13,"gpower":5,"gflag":64,"protection":0,"p_end":1332411629,"status":0,"city":[{"id":23764,"name":"\ub69d\ub531\uc131","landtype":5,"x":264,"y":133},{"id":24410,"name":"\ub69d\ub531\uc1312","landtype":5,"x":265,"y":133}],"conq":[0,0,null,5],"gift":[],"pvp":0},"events":[{"id":1,"icon":"gem.jpg","name":"\uc131\uc2e4\ud55c \ub2f9\uc2e0\uc744 \uc704\ud55c \ubcf4\uc0c1! [5\/7\uc77c]","desc":"<b>\uc77c\uc77c \uc120\ubb3c<\/b>\uc740 \ub85c\uadf8\uc778 \ud6c4 \ubc1b\uc73c\uc2e4 \uc218 \uc788\uc2b5\ub2c8\ub2e4. 7\uc77c\uac04 \uc5f0\uc18d \ub85c\uadf8\uc778\uc744 \ud558\uc2dc\uba74 <b>\ub3d9\uc6d0\ub839(7\uc77c)<\/b>\uc744 \ub4dc\ub9bd\ub2c8\ub2e4!"},{"id":2,"icon":"0.png","name":"\ub4f1\uae09\uaca9\ucc28 \ubcf4\ud638\uc0c1\ud0dc","desc":"\uba3c\uc800 \uacf5\uaca9\ud558\uc9c0 \uc54a\ub294 \uc774\uc0c1, 10\ub4f1\uae09\uc774\uc0c1\uc758 \uc720\uc800\ub85c\ubd80\ud130 \ubcf4\ud638 \ubc1b\uc2b5\ub2c8\ub2e4. \uc774 \ubcf4\ud638\ub294 \ub85c\uadf8\uc544\uc6c3\ud6c4 24\uc2dc\uac04\uc774 \uc9c0\ub098\uba74 \uc790\ub3d9\uc73c\ub85c \ucde8\uc18c\ub429\ub2c8\ub2e4."}],"status":{"invite":1,"ver":0.9,"vs":1.25,"vr":0.5,"ce":1,"he":1}}})

print('사용자 정보 추출')

userinfo_url = '/game/get_userinfo_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

html_source = get_html_response(userinfo_url, 2)

if html_source == '::ERROR::':

    sys.exit()

if '"code":0' in html_source:

    base_city_id = re.search('"city":\[\{"id":(\d+),"name":',html_source).group(1)

    city_id_all  = re.findall('"id":(\d+),"name"', html_source)

    print('사용자 본성 ID : ' + base_city_id)

    print('사용자 전체성 ID : ', end ='')

    print(city_id_all)

else:

    print('사용자 정보 추출에 실패하였습니다!!')

    print('Error Code : ' + html_source)

    sys.exit()


# 사용자 테스크 정보

usertask_url = '/game/system_task_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&action=task_list&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

html_source = get_html_response(usertask_url, 2)

if html_source == '::ERROR::':

    sys.exit()


# 도시정보 호출

city_resource = get_city_resource(base_city_id)

if city_resource == '::ERROR::':

    sys.exit()


# cd 정보??

cdinfo_url = '/game/get_cdinfo_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + base_city_id + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

html_source = get_html_response(cdinfo_url, 2)

if html_source == '::ERROR::':

    sys.exit()


# 사용자 희망 작업 선택!!

print("""

***************************************************************

* 메뉴 선택

***************************************************************

* 1: 오랑캐 좌표 및 현시간 미점령 식량창고(대) 좌표 스캔!!

*    본성에 척후병이 약 100명정도 보유 하셔야 합니다!!

*    초반 성별 식량은 15만 이상 맞춰 주세요!!

*

* 2: ID 정찰결과 함에 존재하는 병력정보 검색(Only산도적 좌표 자동친구추가)

* 3: 도시별 연무장 소문 수집 작업(연무장 레벨 최소 16이상, 고용 공간 필요)

* 4: 친구추가 되어있는 오랑캐 자동사냥

* 5: 종료

***************************************************************


""")


which_way = int(input('원하시는 작업을 선택하여주세요[1 - 4] : '))


if which_way == 1:

    # 오랑캐 추출 갯수 입력부

    base_find_cnt = int(input('얼마나 많은 오랑캐 좌표를 찾길 원하세요?(1-' + str(base_max_cnt) + ') : '))

    if (base_find_cnt < 1) or (base_find_cnt > base_max_cnt):

        print('입력값의 범위가 잘못되었습니다.(입력값은 숫자 1 부터 ' + str(base_max_cnt) + '사이 값이어야 합니다.')

        sys.exit()

    base_find_type = int(input('어떤 종류의 오랑캐를 찾고 싶으세요(1-6)??\n(1:별6개 오랑캐,2:별5개 오랑캐,3:별4개 오랑캐, ...): '))

    if (base_find_type < 1) or (base_find_type > 6):

        print('입력값의 범위가 잘못되었습니다!!(입력값은 숫자 1부터 6사이 값이어야 합니다!!')

        sys.exit()

    point_x = int(input('지도상 x축 스캔시작 좌표 입력[4 - 270](기본값 4) : '))

    if (point_x < 4) or (point_x > 270):

        print('입력값의 범위가 잘못되었습니다!!(입력값은 숫자 4부터 270사이 값이어야 합니다!!')

        sys.exit()

    point_y = int(input('지도상 y축 스캔시작 좌표 입력[4 - 270](기본값 4) : '))

    if (point_y < 4) or (point_y > 270):

        print('입력값의 범위가 잘못되었습니다!!(입력값은 숫자 4부터 270사이 값이어야 합니다!!')

        sys.exit()

    # 지도 스캔 및 오랑캐/식량창고(대) 좌표추출

    print('지도 스캔작업을 시작합니다...')

    ret_val = scan_area_all(base_find_cnt,base_find_type,point_x,point_y)

    if ret_val == '::ERROR::':

        sys.exit()

elif which_way == 2:

    print('입력하신 ID 정찰결과 함으로 부터 병력정보 및 친구추가 작업을 진행합니다...')

    ret_str = get_enemy_info_from_file()

elif which_way == 3:

    print('다음 도시의 연무장에 1시간 5분마다 모든 도시의 한잔하기를 시행합니다!!')

    print('실행중 서버가 불안정 하거나 한잔하기에 필요한 동전이 부족하면 자동 종료됩니다!!')

    print('대상도시 ID : ', end=''); print(city_id_all)

    #GET /game/gen_conscribe_api.php?jsonpcallback=jsonp1333983704456&_=1333983724728&key=c9808b7af18f45e2e6e599ef6a0fcc02&city=23764&_l=kr&_p=SG-IPHONE-KR HTTP/1.1

    #chk_somedrink_url : jsonp1333985951179({"code":0,"ret":{"price":66,"type":3}})

    #GET /game/gen_conscribe_api.php?jsonpcallback=jsonp1333983704457&_=1333983726653&key=c9808b7af18f45e2e6e599ef6a0fcc02&city=23764&action=pub_process&_l=kr&_p=SG-IPHONE-KR HTTP/1.1

    #buy_response : jsonp1334004741746({"code":0,"ret":{"gold":102706,"price":8545,"refresh":3600,"hero":{"gid":205,"p":21,"i":8,"c1":11,"g":3,"c2":300},"rumor":0}})

    #hero gid:아이디, p:공격력, i:지혜력, c1:방어력, c2: 통솔력


    int_drink_tick = 0

    int_mod_sec = 3780 # 1시간 3분


    try:

        f_drink_name = 'drink_log_' + time.strftime('%y%m%d%H%M') + '.dat'

        while True:

            if (int_drink_tick == 0) or (int_drink_tick % int_mod_sec == 0):

                file_drink = open(f_drink_name, 'a')

                for city_id_item in city_id_all:

                    print('현재시간 : ' + time.strftime('%Y-%m-%d %H:%M:%S'))

                    chk_somedrink_url = '/game/gen_conscribe_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + city_id_item + '&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

                    print('chk_somedrink_url : ' + chk_somedrink_url)

                    html_source = get_html_response(chk_somedrink_url, 2)

                    file_drink.write('chk_somedrink_url : ' + chk_somedrink_url + '\n')

                    if html_source == '::ERROR::':

                        sys.exit()

                    if '"code":0' in html_source:

                        if '"refresh":' in html_source:

                            need_refresh_t = int(re.search('"refresh":(\d+),"hero"', html_source).group(1))

                            print('도시[' + city_id_item + ']의 한잔하기 남은 대기시간 : ' + str(need_refresh_t) + '초 입니다.')

                        else:

                            need_refresh_t = 0

                        need_money = re.search('"price":(\d+),"type"', html_source).group(1)

                        file_drink.write('OK[chk] : ' + str(html_source) + '\n')

                    else:

                        print('도시[' + city_id_item + ']의 소문모으기 준비 작업에 실패하였습니다!!')

                        print('Error Code : ' + html_source)

                        file_drink.write('Err[chk] : ' + str(html_source) + '\n')

                    

                    if need_refresh_t == 0:

                        get_city_money = get_city_resource(city_id_item)

                        print('remain money : ' + get_city_money[0][0] + ', need money : ' + need_money)

                        if int(need_money) > int(get_city_money[0][0]):

                            print('한잔하기에 필요한 동전이 부족하여 작업을 종료합니다!!')

                            sys.exit()

                         

                        buy_somedrink_url = '/game/gen_conscribe_api.php?jsonpcallback=jsonp' + get_time() + '&_=' + get_time() + '&key=' + base_token + '&city=' + city_id_item + '&action=pub_process&_l=kr&_p=SG-IPHONE-KR{}HTTP/1.1'.format(urllib.parse.quote(' '))

                        print('buy_somedrink_url : ' + buy_somedrink_url)

                        html_source = get_html_response(buy_somedrink_url, 2)

                        file_drink.write('buy_somedrink_url : ' + buy_somedrink_url + '\n')

                        if html_source == '::ERROR::':

                            sys.exit()

                        if '"code":0' in html_source:

                            print('buy_response : ' + html_source)

                            file_drink.write('OK[buy] : ' + html_source + '\n')

                        else:

                            print('도시[' + city_id_item + ']의 소문모으기 준비 작업에 실패하였습니다!!')

                            print('Error Code : ' + html_source)

                            file_drink.write('Err[chk] : ' + str(html_source) + '\n')

    

                int_drink_tick = 0

                int_drink_tick += 1

                

                time.sleep(1)

                file_drink.close()

            else:

                #print('현재시간 : ' + time.strftime('%Y-%m-%d %H:%M:%S'))

                int_drink_tick += 1

                #print('남은대기 초 : ' + str(int_drink_tick) + '/' + str(int_mod_sec))

                time.sleep(1)

    finally:

        file_drink.close()

elif which_way == 110:

    while True:

        print('사용자 인증키 : ' + base_token)

        print('현재시간_1 : ' + get_time())

        print('현재시간_2 : ' + get_time())

        print('사용자 본성 ID : ' + base_city_id)

        print('사용자 전체성 ID : ', end ='')

        print(city_id_all)

        input_send_str = str(input('send_str(quit is "q") : '))

        if len(input_send_str) > 1:

            input_send_str = input_send_str.format(urllib.parse.quote(' '))

        if input_send_str == 'q':

            break

        html_source = get_html_response(input_send_str, 2)

        if html_source == '::ERROR::':

            sys.exit()

        print('Response : ')

        print(html_source)

    print('테스트 종료!!')

elif which_way == 4:

    

    city_id_loop = ''

    

    # 질문1

    # 오랑캐 타입!! 어떤 오랑캘 잡을지!!

    type_orang = str(input('친구추가된 오랑캐중 어떤 종류의 오랑캐를 공격하고 싶으세요(1-6)??\n(1:별6개, 2:별5개, 3:별4개, 4:별3개, 5:별2개, 6:별1개): '))

    if (type_orang < '1') or (type_orang > '6'):

        print('입력값의 범위가 잘못되었습니다.(입력값은 숫자 1 부터 6사이 값 이어야 합니다.')

        sys.exit()

    # 질문2

    # 공격 병력타입(중보 : 11, 친위 : 15)

    type_soldier = str(input('어떤 병력으로 오랑캐를 공격하시겠습니까??\n(11: 중보병, 15: 친위기병): '))

    if (type_soldier != '11') and (type_soldier != '15'):

        print('입력값의 범위가 잘못되었습니다.(입력값은 11 또는 15 이어야 합니다.')

        sys.exit()

    # 질문3

    # 공격 병력수 100단위로 입력!!(6성 평균 기준 : 중보 : 800, 친위 : 500)

    num_soldier = int(input('몇명의 병력을 공격에 동원하고 싶으세요\n(100단위 입력, 최소300-최대800): '))

    if (num_soldier < 300) or (num_soldier > 800):

        print('입력값의 범위가 잘못되었습니다!!(입력값은 숫자 300부터 800사이 값이어야 합니다!!')

        sys.exit()

    if (num_soldier % 100) != 0:

        print('입력값의 범위가 잘못되었습니다!!(입력값은 100단위로 이루어져야 합니다!!')

        sys.exit()

    

    city_id_loop = copy.deepcopy(city_id_all)


    while city_id_loop:

        # 리스트 마지막 item을 검출!!

        last_city_id = city_id_loop[len(city_id_loop) - 1]

        # 기본대기시간  10분 60초 * 10분 = 600초

        ret_max_timesleep = 600

        

        for idx_city_id in city_id_loop:

            

            print('[' + idx_city_id + ']성의 자동사냥을 시작합니다...')

            

            ret_max_timesleep = auto_attack(idx_city_id, ret_max_timesleep, type_orang, type_soldier, num_soldier)

            # 리턴값 판별!!

            if ret_max_timesleep < 0:

                # 해당 성 자동 사냥 종료

                city_id_loop.pop(city_id_loop.index(idx_city_id))

                print('[' + idx_city_id + ']성은 자동사냥 목록에서 제외됩니다.')

            else:

                if idx_city_id == last_city_id:

                    print('자동사냥 목록에 있는 모든 성의 자동 사냥 턴이 완료 되었습니다!!')

                    print('인터벌 대기 후 재시작 합니다!!')

                    timesleep(300)

                else:

                    print('[' + idx_city_id + ']성의 자동사냥 턴이 완료 되었습니다!!')

                    print('다음성[' + city_id_loop[city_id_loop.index(idx_city_id) + 1] + ']의 자동사냥을 시작합니다!!')

                    rand_timesleep()

    print('자동 사냥 목록에 남은 성이 없습니다!!')

    input('아무키나 누르시면 자동사냥을 종료합니다.')

    sys.exit()


    # 12. 동전 동괴화 작업!!

    #GET /game/get_userinfo_api.php?jsonpcallback=jsonp1334481191259&_=1334481287964&key=a79a44877dece79457f4e78152c3b08f&action=exp&_l=kr&_p=SG-IPHONE-KR HTTP/1.1

    #GET /game/get_userinfo_api.php?jsonpcallback=jsonp1334481191260&_=1334481290297&key=a79a44877dece79457f4e78152c3b08f&action=g_cd&_l=kr&_p=SG-IPHONE-KR HTTP/1.1

    #GET /game/gold_local_market_api.php?jsonpcallback=jsonp1334481191261&_=1334481299554&key=a79a44877dece79457f4e78152c3b08f&city=23764&type=2&num=1&_l=kr&_p=SG-IPHONE-KR HTTP/1.1


elif which_way == 5:

    print('손바닥삼국지 도우미를 종료합니다.')

    sys.exit()


'Study > python' 카테고리의 다른 글

wxpython webview test  (0) 2013.10.05
[연습중]MK RSS 파싱  (0) 2013.09.23
[연습]Python regular expression & sqlite  (0) 2013.09.22
[펌]Unicode In Python, Completely Demystified  (0) 2013.09.18
python ODBC 연결시~  (0) 2013.01.26
Posted by 땡보
2013. 9. 22. 15:45

바람도 살랑 살랑 불고...

머리는 계속 썩어가고 ㅋㅋ

오늘한 학습들 끄적거리기

#!/usr/bin/env python

#-*- coding:utf-8 -*-

'''

    목  적 : Python 정규식 및 sqlite DB 연습

    버  전 : Python 2.7.5

    연습일 : 2013.09.22

    동  작 :

    나눔로또 페이지의 당첨번호 확인 페이지를 기반으로

    모든 회차의 당첨정보를 수집하여 DB파일에 저장한다.

'''


import sqlite3

import os

import re

import urllib2

import sys


class Encode:

    def __init__(self, stdout, enc):

        self.stdout = stdout

        self.encoding = enc

    def write(self, s):

        self.stdout.write(s.encode(self.encoding))


sys.stdout = Encode(sys.stdout, 'utf-8')


def GetHtmlSrc(as_url, as_decode):

    return urllib2.urlopen(as_url).read().decode(as_decode, 'ignore')


def CreateDB(as_dbfilenm):

    if os.path.exists(as_dbfilenm):

        os.remove(as_dbfilenm)


    ls_ddc = u''' CREATE TABLE LOTTO (seq int primary key not null,

                                    num1 int not null,

                                    num2 int not null,

                                    num3 int not null,

                                    num4 int not null,

                                    num5 int not null,

                                    num6 int not null,

                                    winner_cnt int null,

                                    winnings_amt int null,

                                    autowin int null,

                                    manualwin int null,

                                    url_broad varchar(255) null,

                                    url_winning_store varchar(255) null,

                                    regdate datetime default current_timestamp null,

                                    regemp varchar(10) null);  '''

    ret_val = ExecuteSql(as_dbfilenm, u'C', ls_ddc)

    if type(ret_val) == int and ret_val < 0:

        print u'DB 생성에 실패하였습니다!!'

        return -1

    return ret_val


def ExecuteSql(as_dbfilenm, as_sqltype, as_sqlquery):


    if as_sqltype <> u'C' and not os.path.exists(as_dbfilenm):

        print as_dbfilenm + u' 파일이 존재하지 않습니다.'

        return -1


    if as_sqltype == u'C' and os.path.exists(as_dbfilenm):

        print as_dbfilenm + u' 파일이 이미 존재합니다.'

        return 0


    try:

        conn = sqlite3.connect(as_dbfilenm)

        cur = conn.cursor()


        if as_sqltype <> u'S':

            conn.execute(as_sqlquery)

            conn.commit()

            return 0

        else:

            cur.execute(as_sqlquery)

            return cur.fetchall()

    except sqlite3.Error, e:

        print u'Error %s:' % e.args[0]

        if conn:

            conn.rollback()

        return -1

    finally:

        if conn:

            conn.close()


def GetLottoData(al_max_seq, as_dbfilenm):

    ll_page = 1

    while 1:

        list_result = u''

        ls_url = u'http://www.645lotto.net/Confirm/win_all.asp?sGameNo=&amp;eGameNo=&amp;sltPeriod=&amp;sltPeriod2=&page=' + str(ll_page).decode('utf-8', 'ignore')

        print u'URL : ' + ls_url

        html_src = GetHtmlSrc(ls_url, 'euc-kr')

        pattern = u'<tr>\s*?<td class=\"a\"><a href=\"/Confirm/number.asp\?sltSeq=[0-9]+?\">([0-9]+?)</a></td>\s*?<td>([0-9, ]+?)</td>\s*?<td>([0-9]*?)</td>\s*?<td class=\"right\">([0-9,]+?)</td>\s*?<td>([0-9]+?)</td>\s*?<td>([0-9]+?)</td>\s*?<td><a href=\"(.*?)\">[<img src=\"/images/Confirm/movie.jpg\" alt=\"\" style=\"cursor:pointer;\">|\s]*?</a>\s*?</td>\s*?<td class=\"a\"><a href=\"(.*?)\">바로가기</a></td>'

        re_comp_obj = re.compile(pattern)

        list_result = re_comp_obj.findall(html_src, re.DOTALL)


        for i in range(len(list_result)):

            list_result[i] = list(list_result[i])

            list_result[i][0] = int(list_result[i][0])                          #회차

            list_result[i][1] = list_result[i][1].split(u', ')                 #당첨번호

            list_result[i][2] = int(list_result[i][2])                          #일등당첨자수

            list_result[i][3] = int(list_result[i][3].replace(u',',u''))       #당첨금

            list_result[i][4] = int(list_result[i][4])                          #자동

            list_result[i][5] = int(list_result[i][5])                          #수동

            list_result[i][6] = u'http://www.645lotto.net/' + list_result[i][6].replace(u'../', u'') #당첨방송다시보기 주소

            list_result[i][7] = u'http://www.645lotto.net' + list_result[i][7] #일등판매점

            for j in range(len(list_result[i][1])):

                list_result[i][1][j] = int(list_result[i][1][j])

            print list_result[i]


            if list_result[i][0] == al_max_seq:

                print u'모든페이지 탐색 및 데이터 수집 완료!!', u'프로그램을 종료합니다.'

                exit(0)


            ls_insert_query = u'INSERT INTO LOTTO (seq, num1, num2, num3, num4, num5, num6, winner_cnt, winnings_amt, autowin, manualwin, url_broad, url_winning_store, regemp) VALUES ( '


            ls_insert_value = u''

            ls_insert_value = ls_insert_value + unicode(list_result[i][0]) + u', '

            for j in range(len(list_result[i][1])):

                ls_insert_value = ls_insert_value + unicode(list_result[i][1][j]) + u', '

            ls_insert_value = ls_insert_value + unicode(list_result[i][2]) + u', '

            ls_insert_value = ls_insert_value + unicode(list_result[i][3]) + u', '

            ls_insert_value = ls_insert_value + unicode(list_result[i][4]) + u', '

            ls_insert_value = ls_insert_value + unicode(list_result[i][5]) + u', '

            ls_insert_value = ls_insert_value + u'\'' + unicode(list_result[i][6]) + u'\', '

            ls_insert_value = ls_insert_value + u'\'' + unicode(list_result[i][7]) + u'\', '

            ls_insert_value = ls_insert_value + u'\'AUTO\'' + u' '


            ls_insert_query = ls_insert_query + ls_insert_value + u' ); '


            print u'INSERT QUERY : ' + ls_insert_query


            ret_val = ExecuteSql(as_dbfilenm, u'I', ls_insert_query)

            if ret_val <> 0:

                print u'DB Insert 실패!!'

                return -1


            if list_result[i][0] == al_max_seq:

                print u'모든페이지 탐색 및 데이터 수집 완료!!', u'프로그램을 종료합니다.'

                exit(0)

        ll_page = int(ll_page) + 1

        print str(ll_page).decode('utf-8','ignore')


def main():

    ls_dbfilenm = u'test.db'

    ls_sql = u'select max(seq) from LOTTO'

    ret_cur = ExecuteSql(ls_dbfilenm, u'S', ls_sql)

    if type(ret_cur) == int and ret_cur < 0:

        print u'DB 조회에 실패 하였습니다!'

        print u'DB 데이터를 재생성합니다!'

        ret_val = CreateDB(ls_dbfilenm)

        if ret_val <> 0:

            print u'DB 생성에 실패 하였습니다', u'프로그램을 종료합니다!!'

        ret_val = GetLottoData(1, ls_dbfilenm)


    if type(ret_cur) == list and u'None' in unicode(ret_cur[0][0]):

        print u'데이터가 없습니다!', u'데이터를 재수집합니다.'

        ret_val = GetLottoData(1, ls_dbfilenm)


    print unicode(ret_cur[0][0]) + u'회차 이후의 데이터를 수집합니다.'

    ret_val = GetLottoData(ret_cur[0][0], ls_dbfilenm)


    print u'종료!!'


if __name__ == '__main__':

    main()



'Study > python' 카테고리의 다른 글

[연습중]MK RSS 파싱  (0) 2013.09.23
[연습]손바닥삼국지 오토  (0) 2013.09.22
[펌]Unicode In Python, Completely Demystified  (0) 2013.09.18
python ODBC 연결시~  (0) 2013.01.26
Encoding type table  (0) 2012.12.27
Posted by 땡보