Exemple #1
0
def save_image(file_path, file_name, username):
    user = User.objects.get(auth_user__username=username)
    photo = Photo()
    photo.user = user
    photo.name = file_name
    hasher = hashlib.sha1()
    with open(file_path, 'rb') as afile:
        buf = afile.read()
        hasher.update(buf)
        photo.sha1sum = hasher.hexdigest()
        photo.size = os.path.getsize(file_path)

    if not Photo.objects.filter(sha1sum=photo.sha1sum):
        img = PIL.Image.open(file_path)
        for key_number, v in img._getexif().items():
            if key_number in PIL.ExifTags.TAGS:
                # rstrip fix this error:
                # A string literal cannot contain NUL (0x00) characters
                try:
                    v = str(v).rstrip(' \t\r\n\0')
                    k = PIL.ExifTags.TAGS[key_number]
                    if k == "ExifImageWidth":
                        photo.exif_image_width = v
                    if k == "ExifImageHeight":
                        photo.exif_image_height = v
                    if k == "Make":
                        photo.exif_make = v
                    if k == "Model":
                        photo.exif_model = v
                    if k == "LensMake":
                        photo.exif_lens_make = v
                    if k == "LensModel":
                        photo.exif_lens_model = v
                    if k == "ExifVersion":
                        photo.exif_version = v
                    if k == "SubjectLocation":
                        photo.exif_subject_location = v
                    if k == "DateTime":
                        datetime = v.split(" ")[0].replace(":", "-")
                        photo.exif_datetime = datetime
                    if k == "DateTimeOriginal":
                        datetime_original = v.split(" ")[0].replace(":", "-")
                        photo.exif_datetime_original = datetime_original
                        photo.classification(file_name, file_path)
                    if k == "DateTimeDigitized":
                        datetime_digitized = v.split(" ")[0].replace(":", "-")
                        photo.exif_datetime_digitized = datetime_digitized
                except Exception as e:
                    print("------------------Error----------------------" +
                          str(e))
            else:
                print("Error key number: " + str(key_number))

        photo.save()
    else:
        print("File already Exists")
Exemple #2
0
 def test_set_thumbnail(self):
     """Tests that a thumbnail is generated."""
     with open('tests/testdata/small_image.png') as image_file:
         photo = model.Photo.create('haiti', image_data=image_file.read())
     photo.save()
     self.go('/haiti/tasks/thumbnail_preparer')
     doc = self.s.go('/haiti/photo?id=%s&thumb=true' %
                     photo.key().name().split(':')[1])
     image = images.Image(doc.content_bytes)
     assert image.format == images.PNG
     assert image.height == MAX_THUMBNAIL_DIMENSION
     assert image.width == MAX_THUMBNAIL_DIMENSION
Exemple #3
0
    def post(self, request, *args, **kwargs):
        photo_ids = request.POST.get('selected_images')
        gallery_title = self.kwargs['title']
        gallery = Gallery.objects.get(title=gallery_title)

        for photo in self.get_queryset():
            photo.galleries.remove(gallery)
            photo.save()

        for photo_id in photo_ids.split(','):
            photo = Photo.objects.get(pk=photo_id)
            photo.galleries.add(gallery)
            photo.save()

        return redirect('photo:gallery', title=gallery_title)
Exemple #4
0
    def POST(self):
        str_xml = web.data()
        xml     = etree.fromstring(str_xml)
        msgType = xml.find("MsgType").text
        fromUser= xml.find("FromUserName").text
        toUser  = xml.find("ToUserName").text

        if msgType=='event':
            event = xml.find("Event").text
            if event == 'subscribe' :
                return render.weixin(
                    fromUser, toUser, int(time.time()), hanzi.hello)

        elif msgType=='text' :
            content  = xml.find("Content").text
            sendtext(content)
            return render.weixin(fromUser,toUser,int(time.time()),hanzi.txtok)

        elif msgType=='image':
            pic_url  = xml.find("PicUrl").text
            msg_id   = xml.find("MsgId").text
            info     = photo.save(pic_url, msg_id)
            if info == 1:
                return render.weixin(fromUser,toUser,int(time.time()),hanzi.picok)
            else:
                return render.weixin(fromUser,toUser,int(time.time()),info)

        else:
            return render.weixin(fromUser,toUser,int(time.time()),hanzi.cnfse)
Exemple #5
0
 def test_skip_thumbnail_for_small_enough_images(self):
     """Tests that a thumbnail isn't generated for small enough images."""
     with open('tests/testdata/tiny_image.png') as image_file:
         photo = model.Photo.create('haiti', image_data=image_file.read())
     photo.save()
     self.go('/haiti/tasks/thumbnail_preparer')
     db_photo = model.Photo.get_by_key_name(photo.key().name())
     # tiny_image.png is 40x40, so it shouldn't bother generating a
     # thumbnail.
     assert not db_photo.thumbnail_data
     doc = self.s.go('/haiti/photo?id=%s&thumb=true' %
                     photo.key().name().split(':')[1])
     image = images.Image(doc.content_bytes)
     assert image.format == images.PNG
     assert image.height == 40
     assert image.width == 40
Exemple #6
0
    def POST(self):
        str_xml = web.data()
        xml = etree.fromstring(str_xml)
        msgType = xml.find("MsgType").text
        fromUser = xml.find("FromUserName").text
        toUser = xml.find("ToUserName").text
        if msgType == 'event':
            event = xml.find("Event").text
            if event == 'subscribe':
                return render.weixin(fromUser, toUser, int(time.time()),
                                     hanzi.hello)
            elif event == 'unsubscribe':
                db.delete('info', where="weixin_id=$fromUser", vars=locals())
            else:
                pass
        elif msgType == 'text':
            content = xml.find("Content").text
            id = db.select('info',
                           what="id",
                           where="weixin_id=$fromUser",
                           vars=locals())
            if len(id) == 0:
                if len(content) > 50:
                    return render.weixin(fromUser, toUser, int(time.time()),
                                         hanzi.hello)
                else:
                    code, xiezhua_xml = xiezhua(content.strip(), hanzi.bind_ok,
                                                hanzi.weixin, 'talk')
                    if code != 200:
                        return render.weixin(fromUser, toUser,
                                             int(time.time()),
                                             str(code) + hanzi.hello)
                    else:
                        xml0 = etree.fromstring(xiezhua_xml)
                        id = xml0[0][6][0].text
                        db.insert('info',
                                  id=id,
                                  weixin_id=fromUser,
                                  xiezhua_id=content,
                                  sendfrom=hanzi.weixin)
                        return render.weixin(fromUser, toUser,
                                             int(time.time()), hanzi.bind_ok)
            else:
                xiezhua_id = db.select('info',
                                       what="xiezhua_id",
                                       where="weixin_id=$fromUser",
                                       vars=locals())
                sendfrom = db.select('info',
                                     what="sendfrom",
                                     where="weixin_id=$fromUser",
                                     vars=locals())
                if content == 'help':
                    return render.weixin(fromUser, toUser, int(time.time()),
                                         hanzi.help)
                elif content[0:8:] == 'sendfrom':
                    sendfrom = content[8::]
                    db.update('info',
                              where="weixin_id=$fromUser",
                              sendfrom=sendfrom,
                              vars=locals())
                    sendfrom = db.select('info',
                                         what="sendfrom",
                                         where="weixin_id=$fromUser",
                                         vars=locals())
                    if sendfrom[0].sendfrom == content[8::]:
                        code, xiezhua_xml = xiezhua(
                            xiezhua_id[0].xiezhua_id,
                            hanzi.sendfrom_ok + content[8::], content[8::],
                            'talk')
                        return render.weixin(fromUser, toUser,
                                             int(time.time()),
                                             hanzi.sendfrom_ok + content[8::])
                    else:
                        return render.weixin(fromUser, toUser,
                                             int(time.time()),
                                             hanzi.sendfrom_fail)
                        code, xiezhua_xml = xiezhua(
                            xiezhua_id[0].xiezhua_id, hanzi.sendfrom_fail,
                            sendfrom[0].sendfrom.encode('raw_unicode_escape'),
                            'talk')

                elif content == hanzi.timeline:
                    timeline = db.select('info',
                                         what="timeline",
                                         where="weixin_id=$fromUser",
                                         vars=locals())
                    timeline, string = timeline.get_string(
                        xiezhua_id, timeline)
                    if timeline == 0:
                        return render.weixin(fromUser, toUser,
                                             int(time.time()), hanzi.nomore)
                    else:
                        db.update('info',
                                  where="weixin_id=$fromUser",
                                  timeline=timeline,
                                  vars=locals())
                        return render.weixin(fromUser, toUser,
                                             int(time.time()), string)

                else:
                    code, xiezhua_xml = xiezhua(xiezhua_id[0].xiezhua_id,
                                                content, sendfrom[0].sendfrom,
                                                'talk')
                    if code == 200:
                        return render.weixin(fromUser, toUser,
                                             int(time.time()), hanzi.send_ok)
                    else:
                        db.delete('info',
                                  where="weixin_id=$fromUser",
                                  vars=locals())
                        return render.weixin(fromUser, toUser,
                                             int(time.time()), hanzi.hello)

        elif msgType == 'image':
            picurl = xml.find("PicUrl").text
            msgid = xml.find("MediaId").text
            photo.save(msgid, picurl)
            id = db.select('info',
                           what="id",
                           where="weixin_id=$fromUser",
                           vars=locals())
            if len(id) == 0:
                return render.weixin(fromUser, toUser, int(time.time()),
                                     hanzi.hello)
            else:
                xiezhua_id = db.select('info',
                                       what="xiezhua_id",
                                       where="weixin_id=$fromUser",
                                       vars=locals())
                sendfrom = db.select('info',
                                     what="sendfrom",
                                     where="weixin_id=$fromUser",
                                     vars=locals())
                pic = urllib2.urlopen(picurl).read()
                code, xiezhua_xml = xiezhua(
                    xiezhua_id[0].xiezhua_id,
                    '''[img]''' + picurl + '''[/img]''', sendfrom[0].sendfrom,
                    'talk')
                if code == 200:
                    return render.weixin(fromUser, toUser, int(time.time()),
                                         hanzi.send_ok)
Exemple #7
0
def loginn(name, pwd):
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--headless')
    browser = webdriver.Chrome(chrome_options=chrome_options)
    browser.get('https://user.qzone.qq.com')

    #跳转到用户名密码形式
    browser.switch_to_frame('login_frame')
    log = browser.find_element_by_id("switcher_plogin")
    log.click()
    time.sleep(0.5)

    #定位用户名框并输入
    use = browser.find_element_by_id('u')
    use.send_keys(name)

    #定位密码框并输入,判断是否登录成功
    ps = browser.find_element_by_id('p')
    ps.send_keys(pwd)
    btn = browser.find_element_by_id('login_button')
    time.sleep(0.5)
    btn.click()
    time.sleep(0.5)
    right = 'https://user.qzone.qq.com/' + name
    now_url = browser.current_url
    if now_url == right:
        print('登录成功')

        #跳转到我的主页
        inf = browser.find_element_by_link_text("我的主页")
        inf.click()

        #获得cookie
        cookie = {}
        hashes = 5381
        for i in browser.get_cookies():
            cookie[i["name"]] = i["value"]

#计算gtk
        for letter in cookie['p_skey']:
            hashes += (hashes << 5) + ord(letter)
        hashes = hashes & 0x7fffffff
        hashes = str(hashes)

        #获得token
        html = browser.page_source
        g_qzonetoken=re.search('window\.g_qzonetoken'+\
                               ' = \(function\(\)\{ try\{return (.*?);\} catch\(e\)',html)
        g_qzonetoken = str(g_qzonetoken[0]).split('\"')[1]
        g_qzonetoken = str(g_qzonetoken)

        #获得个人信息url写到本地
        url =  'https://h5.qzone.qq.com/proxy/domain/base.qzone.qq.com'+\
              '/cgi-bin/user/cgi_userinfo_get_all?uin='+name+\
              '&vuin='+name+'&fupdate=1&rd='+'0.7137596336600174'+\
              '&g_tk='+hashes+'&qztoken='+g_qzonetoken
        page = browser.get(url)
        html1 = browser.page_source
        info.inf(html1)

        #获取好友列表并保存在本地
        url = 'https://user.qzone.qq.com/proxy/dom'+\
              'ain/r.qzone.qq.com/cgi-bin/tfriend/f'+\
              'riend_ship_manager.cgi?uin='+name+\
              '&do=1&rd=0.07649617356193117&fupd'+\
              'ate=1&clean=1&g_tk='+hashes+'&qzonetoken='+\
              g_qzonetoken+'&g_tk='+hashes
        page = browser.get(url)
        html = browser.page_source
        flist.then(html)

        #获得相册html,调用保存函数
        url1 = 'https://h5.qzone.qq.com/proxy/domain/photo.qzon'+\
               'e.qq.com/fcgi-bin/fcg_list_album_v3?g_tk='+\
               hashes+'&callback=shine0_Callback&t=26152317'+\
               '9&hostUin='+name+'&uin='+name+\
               '&appid=4&inCharset=utf-8&outCharset=utf-8&source=qzone&plat=qzone'\
               +'&format=jsonp&notice=0&filter=1&handset=4&pageNumModeSort=40&'+\
               'pageNumModeClass=15&needUserInfo=1&idcNum=4&callback'+\
               'Fun=shine0&_=1533627125951'
        time.sleep(1)
        page = browser.get(url1)
        html = browser.page_source
        time.sleep(1)
        pid = re.findall('"id" : "(.*?)"', html)
        count = 0
        time.sleep(1)
        for i in pid:
            alid = i
            url =  'https://h5.qzone.qq.com/proxy/domain/photo.qzone.'+\
                  'qq.com/fcgi-bin/cgi_list_photo?g_tk='+hashes+'&callback'+\
                  '=shine0_Callback&t=984071564&mode=0&idcNum=4'+\
                  '&hostUin='+name+'&topicId='+alid+'&noTopic=0&uin='+name+\
                  '&pageStart=0&pageNum=30&skipCmtCount=0&singleurl='+\
                  '1&batchId=&notice=0&appid=4&inCharset=utf-8&outCharset='+\
                  'utf-8&source=qzone&plat=qzone&outstyle=json&format=jsonp&json_esc=1&questi'+\
                  'on=&answer=&callbackFun=shine0&_=1533781622395'
            page = browser.get(url)
            html = browser.page_source
            time.sleep(2)
            photo.save(html, count)
            count += 1
        print('相册存储成功')

        #获得说说
        url = 'https://user.qzone.qq.com/proxy/'+\
              'domain/taotao.qq.com/cgi-bin/emo'+\
              'tion_cgi_msglist_v6?uin='+name+'&ftype=0&s'+\
              'ort=0&pos=0&num=20&replynum=100&g_tk='+hashes+\
              '&callback=_preloadCallback&code_version=1&f'+\
              'ormat=jsonp&need_private_comment=1&qzonetoken='+\
              g_qzonetoken+'&g_tk='+hashes
        page = browser.get(url)
        html = browser.page_source
        undergo.then(html)
        browser.quit()

    else:
        print('账号或密码错误')
        browser.quit()
Exemple #8
0
    def POST(self):
        str_xml = web.data() 
        xml     = etree.fromstring(str_xml)
        msgType = xml.find("MsgType").text
        fromUser= xml.find("FromUserName").text
        toUser  = xml.find("ToUserName").text
        if   msgType == 'event':
            event = xml.find("Event").text
            if   event == 'subscribe'  :
                return render.weixin(fromUser,toUser,int(time.time()),hanzi.hello)
            elif event == 'unsubscribe':
                db.delete('info', where="weixin_id=$fromUser",vars=locals())
            else:
                pass
        elif msgType == 'text' :
            content  = xml.find("Content").text
            id       = db.select('info' ,what="id"      ,where="weixin_id=$fromUser",vars=locals())
            if len(id) == 0:
                if len(content) > 50:
                    return render.weixin(fromUser,toUser,int(time.time()),hanzi.hello)
                else:
                    code,xiezhua_xml = xiezhua(content.strip(),hanzi.bind_ok,hanzi.weixin,'talk')
                    if code != 200:
                        return render.weixin(fromUser,toUser,int(time.time()),str(code)+hanzi.hello)
                    else:
                        xml0 = etree.fromstring(xiezhua_xml)
                        id   = xml0[0][6][0].text
                        db.insert('info', id=id ,weixin_id=fromUser ,xiezhua_id=content ,sendfrom=hanzi.weixin)
                        return render.weixin(fromUser,toUser,int(time.time()),hanzi.bind_ok)
            else:
                xiezhua_id = db.select('info' ,what="xiezhua_id",where="weixin_id=$fromUser" ,vars=locals())
                sendfrom   = db.select('info' ,what="sendfrom"  ,where="weixin_id=$fromUser" ,vars=locals())
                if   content == 'help':
                    return render.weixin(fromUser,toUser,int(time.time()),hanzi.help)
                elif content[0:8:] == 'sendfrom':
                    sendfrom = content[8::]
                    db.update('info' ,where="weixin_id=$fromUser" ,sendfrom=sendfrom ,vars=locals())
                    sendfrom = db.select('info',what="sendfrom"  ,where="weixin_id=$fromUser" ,vars=locals())
                    if sendfrom[0].sendfrom == content[8::]:
                        code,xiezhua_xml = xiezhua(xiezhua_id[0].xiezhua_id,hanzi.sendfrom_ok+content[8::],content[8::],'talk')
                        return render.weixin(fromUser,toUser,int(time.time()),hanzi.sendfrom_ok+content[8::])
                    else:
                        return render.weixin(fromUser,toUser,int(time.time()),hanzi.sendfrom_fail)
                        code,xiezhua_xml = xiezhua(xiezhua_id[0].xiezhua_id,hanzi.sendfrom_fail,sendfrom[0].sendfrom.encode('raw_unicode_escape'),'talk')

                elif content==hanzi.timeline:
                    timeline = db.select('info',what="timeline",where="weixin_id=$fromUser" ,vars=locals())
                    timeline,string = timeline.get_string(xiezhua_id,timeline)
                    if timeline == 0:
                        return render.weixin(fromUser,toUser,int(time.time()),hanzi.nomore)
                    else:
                        db.update('info' ,where="weixin_id=$fromUser" ,timeline=timeline ,vars=locals())
                        return render.weixin(fromUser,toUser,int(time.time()),string)
                    
                else:
                    code,xiezhua_xml = xiezhua(xiezhua_id[0].xiezhua_id,content,sendfrom[0].sendfrom,'talk')
                    if code == 200:
                        return render.weixin(fromUser,toUser,int(time.time()),hanzi.send_ok)
                    else:
                        db.delete('info', where="weixin_id=$fromUser" ,vars=locals())
                        return render.weixin(fromUser,toUser,int(time.time()),hanzi.hello)

        elif msgType == 'image' :
            picurl   = xml.find("PicUrl").text
            msgid   = xml.find("MediaId").text
            photo.save(msgid,picurl)
            id       = db.select('info' ,what="id"      ,where="weixin_id=$fromUser",vars=locals())
            if len(id) == 0:
                return render.weixin(fromUser,toUser,int(time.time()),hanzi.hello)
            else:
                xiezhua_id = db.select('info' ,what="xiezhua_id",where="weixin_id=$fromUser" ,vars=locals())
                sendfrom   = db.select('info' ,what="sendfrom"  ,where="weixin_id=$fromUser" ,vars=locals())
                pic        = urllib2.urlopen(picurl).read()
                code,xiezhua_xml = xiezhua(xiezhua_id[0].xiezhua_id,'''[img]'''+picurl+'''[/img]''',sendfrom[0].sendfrom,'talk')
                if code == 200:
                    return render.weixin(fromUser,toUser,int(time.time()),hanzi.send_ok)