Exemple #1
0
def get_code(request):

    form = CodeForm(request.GET)
    if not form.is_valid():
        return HttpResponse(form.errors.pop('phone_num'))    
    else :
        phone_num = form.cleaned_data.get('phone_num')    
        fid = form.fid
    import random
    chars = 'abcdefghjklmnpqrstuvwxyz123456789'.upper() * 5
    code = ''.join(random.sample(chars, 6))
    t = loader.get_template('sms.html')
    sms = t.render(Context({'code': code}))
    
#    phone = settings.FETION[0][0]
#    psw = settings.FETION[0][1]
#    ft = Fetion(phone, psw, cachefile=None)
#    
    ft = MyFetion(PHONE,PSW)    
    #发送验证码,注意消息需要用utf-8编码
    if ft.sendBYid(fid, sms.encode('utf-8'), True) :
        #设置session
        request.session['phone_num'] = phone_num
        request.session['code'] = code
        request.session.set_expiry(300)                        
        msg = '验证码已发送到你的手机,请在5分钟内输入,不区分大小写。\n如果30秒内没有收到,请点击重新获取\n[飞信天气网:http://tq.sms128.net]' 
    else :
        msg = 'something wrong,retry please'
        
    ft.logout()
    return HttpResponse(msg)
Exemple #2
0
 def clean_phone_num(self):
     
     phone_num = self.cleaned_data['phone_num']
     Log(level=2,event='%s tried to subscribe' % phone_num).save()        
     #self.phone_num = phone_num
     china_mobile_num = ('134','135','136','137','138','139','150','151','152','158','159','157','187','188','147')
     if phone_num[0:3] not in china_mobile_num:
         raise ValidationError('非中国移动号码不能注册')
     try:            
         user = User.objects.get(phone_num=phone_num)
     except User.DoesNotExist:
         pass
     else :
         if user.active == True :
             raise ValidationError('你已经注册过了')
         else :
             raise ValidationError('帐户已冻结,请激活后继续使用')
     
     #这里的管理员手机可能使用模型存取
     phone = FETION[0][0]
     psw = FETION[0][1]
     ft = MyFetion(phone, psw)
     fid = ft.findid(phone_num)
     ft.logout()
     if fid == None:
         raise ValidationError('无效手机号或没有开通飞信服务')
     else :
         
         self.fid = fid
         return phone_num
Exemple #3
0
def sendGroupSms(weather):
    clock_dt = _current_clock_dt()
    users = weather.user_set.filter(active=True,phone_num="13714681456")
    
    if len(users)>0 :
        try:
            ft = MyFetion(PHONE,PSW)            
                                
            for u in users :
                message = parse_json(weather.info,u)
                
                if message == False:
                    Log(level=0,event='json数据解析出错:订阅天气信息%s:s%' %(weather.cid,weather.hour)).save()
                    return False    
                
                if message == None :
                    continue
                send_result = ft.sendBYid(u.fid, message.encode('utf-8'))
                if send_result == True :  #发送计数
                    global send_count
                    send_count += 1
                #返回none表示非好友,对非好友不重复发送                 
                if send_result == True or send_result == None:

                    did = "Did" if send_result == True else "Didn't"
                    u.send_time = datetime.now()
                    u.save()                    
                    Log(level=2,event = '%s Send to %s[%sh]:%s:(%s)' % (did,u.phone_num,weather.hour,weather.cid.city,message)).save()
        except Exception,e :            
            print "except Happen: ",e
            if 'ft' in locals():
                ft.logout()
Exemple #4
0
 def run(self):
     limit = 5
     u = User.objects.get(phone_num='13714681456')
     for i in range(limit):
         try:
             ft = MyFetion(PHONE,PSW,False)
             if ft.sendBYid(u.fid,'My thread name is %s' % self.getName() ,True) == True:
                 break
             else :
                 i+=1
         except:
             i+=1
             err_info = sys.exc_info()
             log = '%s : %s' % (err_info[0],err_info[1])
     
         finally:
             if 'ft' in locals():
                 ft.logout()
         
     else:
         print "5次尝试结束,记入日志 " + log
Exemple #5
0
def index(request):
    msg = '请先填写手机号码和订阅信息, 天气短信将发送到你的手机。'
    if request.method == 'POST':
        form = SubscribeForm(request.POST)            
        if form.is_valid():
            fid = form.fid
            cd = form.cleaned_data
            
            
            #向天气订阅表增加记录或找出指定城市的订阅实例
            try:
                weather = Weather.objects.get(cid=cd['city'], hour=cd['hour'])
            except Weather.DoesNotExist:
                city = City.objects.get(cid=cd['city'])
                weather = Weather(cid=city, hour=cd['hour'])
                weather.save()
            
            #发送加为好友的短信
            ft = MyFetion(PHONE,PSW)
            add_res = ft.addfriend(cd['phone_num'], NICK, '2')
            if add_res:
                Log(level=2,event='success to send adding friend sms to %s' % cd['phone_num']).save()
            else:
                Log(level=1,event='failed to send adding friend sms to %s ,maybe he/she has been your friend.' % cd['phone_num']).save()

            #用户与天气订阅表关联,仅使用新增            
            user = User(fid=fid, phone_num=cd['phone_num'], wid=weather, sub_type=cd['sub_type'], active=True)
            user.save()            
            
            if add_res:
                msg = '你将收到一条"%s"的好友请求短信,请于24小时内确认,逾期无效' %  NICK
            else:
                msg = '订制成功'
            form = None
    
    else:    
        default_hour = int(strftime('%H')) + 1
        form = SubscribeForm(initial={'hour':default_hour, 'sub_type':'E'}) #定义字段的option默认值        
    return render_to_response('index.html', {'form':form, 'msg':msg, 'form_id':'subscribe'}, context_instance=RequestContext(request))
Exemple #6
0
def sendGroupSms(weather):
    users = weather.user_set.filter(active=True)
    #print len(users)
    if len(users)>0 :
        try:
            ft = MyFetion(PHONE,PSW)            
                                
            for u in users :
                message = parse_json(weather.info,u)
                if message == False:
                    Log(level=0,event='json数据解析出错:订阅天气信息%s:s%' %(weather.cid,weather.hour)).save()
                    return False    
                
                if message == None :
                    continue
                               
                ft.sendBYid(u.fid, message.encode('utf-8'))
                print 'send to %s : %s' % (u.phone_num,message)
                Log(level=2,event = 'Send to %s[%sh]:%s:(%s)' % (u.phone_num,weather.hour,weather.cid.city,message)).save()
        except:
            if 'ft' in locals():
                ft.logout()
Exemple #7
0
def sendGroupSms(weather):
    clock_dt = current_clock_dt()
    users = weather.user_set.filter(active=True,send_time__lt=clock_dt)[0:10] #limit to 10 users/min 
    
    if len(users)>0 :
        try:
            #print PHONE,PSW
            ft = MyFetion(PHONE,PSW)            
                                
            for u in users :
                message = parse_json(weather.info,u)
                
                if message == False:
                    Log(level=0,event='json data parse error: %s:s%' %(weather.cid,weather.hour)).save()
                    return False    
                
                if message == None :
                    continue
                send_result = ft.sendBYid(u.fid, message.encode('utf-8'))
                if send_result == True :  #发送计数
                    global send_count
                    send_count += 1
                #返回none表示非好友,对非好友不重复发送                 
                if send_result == True or send_result == None:

                    did = "Did" if send_result == True else "Didn't"
                    u.send_time = datetime.now()
                    u.save()                    
                    Log(level=2,event = '%s Send to %s[%sh]:%s:(%s)' % (did,u.phone_num,weather.hour,weather.cid.city,message)).save()
        except Exception,e :            
#            print "except Happen: ",e
            Log(level=0,event='exception happen :%s' % traceback.print_exc()).save()
            
#            raise e
            if 'ft' in locals():
                ft.logout()
Exemple #8
0
#!/home/dotcloud/env/bin/python
#coding:utf-8

import sys,os,threading,time,urllib2,json
from datetime import datetime,timedelta

#only use in dotcloud 
package_dir = '/home/dotcloud/env/lib/python2.6/site-packages'
if os.path.exists(package_dir):
    sys.path.append(package_dir)

current_dir = os.path.dirname(__file__)
settings_dir = os.path.abspath(os.path.join(current_dir,os.path.pardir))
if settings_dir not in sys.path :
    sys.path.append(settings_dir)
import settings
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
os.environ['TZ'] = settings.TIME_ZONE
from weather.models import MyFetion, Log, User,City,Weather 

PHONE = settings.FETION[0][0]
PSW = settings.FETION[0][1]

ft = MyFetion(PHONE,PSW)
fid = ft.findid('13686892480')
print fid
fid = ft.findid('13480999585')
print fid

def send_alarm_sms():
    #组装飞信发送列表,测试数据为2012月7月2日12时
    clock = datetime(2012,7,2,16,0,0,0) if MODE == 'TEST' else current_clock_dt()    
    current_alarms = Alarm.objects.filter(pub_time=clock)    
    to_send_list = []
    for current_alarm in current_alarms :
        # if is_ignore_city(current_alarm.title):
            # continue
        '''省级预警存在市级行政区字样时忽略'''    
        if len(current_alarm.area_code) == 5 and in_ignore_text(current_alarm.title):
            continue
        users = User.objects.filted_with_cid(current_alarm.area_code)
        if (len(users)>0 and current_alarm.content == ''):
            current_alarm.content = Alarm.fetch_content(current_alarm.url)
            current_alarm.save()
        for user in users:
            try:
                alarm_log = AlarmLog.objects.get(alarm=current_alarm,user=user)
                continue
            except:
                to_send_list.append((user,current_alarm))                
    #开始发送(单线程)
    send_count = 0
    if len(to_send_list) > 0 :
        for i in range(0,LOGIN_LIMIT):
            try:
                ft = MyFetion(PHONE,PSW)
                break
            except:i+=1         
        else:
            Log(level=1,event="failed to initial MyFetion in sending sms")
            sys.exit(1)
        #这里可以一次最大发送量
        for user,alarm in to_send_list[0:SEND_MAX]:
            fid = MyFetion.test_id if MODE == 'TEST' else user.fid
            tail = u'via飞信天气网(预警短信Beta)'
            content = u'[%s]\n%s %s' % (alarm.title,alarm.content,tail)            
            #测试和开发时给自己发送
            #if MODE != 'PRODUCT':pass
            details = u'status:ready %s-%s:%s'  %(user.phone_num,alarm.area_code,content)
            #保证先写入库成功再发送,不会造成重复发送,入库时失败,不会向该用户发送
            #但是存在一个问题,即入库成功,但发送失败,即下面的sendBYid失败后,不会再向该用户发送
            #如果脚本在sendBYid中断,日志信息(details列)也不会获得更新,即使是发送成功,也会显示status:failed。
            try:                
                AlarmLog(alarm=alarm,user=user,details=details).save()
            except Exception,e :
                error_msg = 'alarmlog write to db error:%s:%s:%s' % (e,alarm,user)
                Log(level=0,event = error_msg).save()
                if MODE != 'PRODUCT': print error_msg  
            else:
                send_result = ft.sendBYid(fid, content.encode('utf-8'))            
                if send_result == True or send_result == None: 
                    send_count +=1
                    did = "OK" if send_result == True else "Failed"
                    details = 'status:%s,%s,area_code:%s,content:%s' % (
                    did,user.phone_num,alarm.area_code,content)
                    AlarmLog.objects.filter(
                    alarm=alarm,user=user).update(details=details)
            #将发送结果发给自己        
            ft.send2self(details.encode('utf-8'))
            if MODE != 'PRODUCT': print user.phone_num,content        
        ft.logout()