Source

VPlayer / note.py

Full commit
# -*- coding: utf-8 -*-

import re
import time
import urllib, urllib2

from track import Track
from logininfo import LoginInfo
from htmldecoder import decode_entities

class NoteLoadError(Exception):
    pass

class NoteSaveError(Exception):
    pass

class ServerError(Exception):
    pass


class Note:
    title = None
    tracks = []
    hash = None
    
    def __init__(self, login, title = None, tracks = [], hash = None,
                 exists = False, nid = None):
        self.login = login
        self.title = title
        self.tracks = tracks
        self.hash = hash
        self.exists = exists
        self.nid = nid
        self.url = 'http://vkontakte.ru/notes.php'
        self.headers = {'User-agent': 'Mozilla/5.0 (X11; U;\
        Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko,\
        Safari/419.3) Arora/0.6',
        'Cookie': self.login.cookies }
        
    def save(self):
        if not self.hash:
            self.get_hash()
        data = {}
        data['Post'] = self.form_note_text(self.tracks)
        data['hash'] = self.hash
        data['visible'] = 0
        data['commentable'] = 0
        title = str()
        if not self.title:
            if self.tracks:
                title = self.tracks[0].title
        else: title = self.title
        if len(title)>65:
            title = title[0:64]
        if not title:
            title = 'Playlist'
        data['title'] = title
        if not self.exists:
            data['act'] = "add" 
            data['preview'] = 0
        else:
            data['act'] = "update"
            data['nid'] = self.nid
        post = urllib.urlencode(data)
        req = urllib2.Request(self.url, post, self.headers)
        urlreq = urllib2.urlopen(req)
        pagetext = urlreq.read()
        if not self.exists:
            if not u'Новая заметка добавлена.' in unicode(pagetext, 'cp1251'):
                raise NoteSaveError()
            notes = re.findall('<div class="note_title">[\t\n\ ]*<a href="note\d+\_(\d+)">[^<]*</a>[\t\n\ ]*</div>', pagetext)
            if len(notes) < 1: raise ServerError()
            self.nid = int(notes[0])
            self.exists = True
            return
        else:
            if not u'Заметка отредактирована.' in unicode(pagetext, 'cp1251'):
                raise NoteSaveError()
    
    def load(self, nid = None):
        if nid is None:
            nid = self.nid
        if nid is None:
            raise TypeError()
        self.tracks = []
        url = 'http://vkontakte.ru/note'+str(self.login.id)+'_'+str(nid)
        req = urllib2.Request(url, headers = self.headers)
        urlreq = urllib2.urlopen(req)
        pagetext = urlreq.read()
        titles = re.findall('<div class="note_title">[\n\t\ ]*<a href="note\d+_\d+">([^<]*)</a>[\n\t\ ]*</div>', pagetext)
        if len(titles) != 1:
            raise NoteLoadError()
        title = titles[0]
        self.title = title
        tracklist = re.findall("""<img class="playimg" onclick="return operateWall\((\d+),(\d+),(\d+),'([\w\d]*)',(\d+)\);" id="imgbuttonWall\d+" nosorthandle="true" src="/images/play.gif"></td> <td style="width: 290px;"><div style="float: left;"> <b id="performerWall\d+">([^<]*)</b> - <span id="titleWall\d+">([^<]*)</span></div>""", pagetext)
        for info in tracklist:
            server = info[1]
            user = info[2]
            fname = info[3][1:-1]
            length = info[4]
            aid = int(info[0])
            oid = int(info[2])
            artist = info[5]
            title = info[6]
            link = 'http://cs' + server + '.vkontakte.ru/u' + user\
            + '/audio/' + fname + '.mp3'
            track = Track(decode_entities(unicode(artist,'cp1251')),
                          decode_entities(unicode(title,'cp1251')),
                          unicode(link,'cp1251'),
                          unicode(length,'cp1251'), aid, oid)
            self.tracks.append(track)
        self.exists = True

    def form_note_text(self, tracks = None):
        if not tracks: tracks = self.tracks
        text = str()
        for track in tracks:
            text += '[[audio'+str(track.aid)+'_'+str(track.oid)+']]'
        return text

    def get_hash(self):
        url = 'http://vkontakte.ru/notes.php?act=new'
        headers = {'User-agent': 'Mozilla/5.0 (X11; U;\
                    Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko,\
                    Safari/419.3) Arora/0.6',
                    'Cookie': self.login.cookies }
        req = urllib2.Request(url, headers=headers)
        urlreq = urllib2.urlopen(req)
        page = urlreq.read()
        results = re.findall('<input type="hidden" name="hash" id="hash" value="([a-z0-9]*)">', page)
        if len(results) == 0:
            print page
            raise ServerError()
        self.hash = results[0]
        return self.hash
l = LoginInfo('mytestmail@slopsbox.com', '36187077', 'gfhjkm')
n = Note(l)
n.load(nid = 8775392)
for track in n.tracks:
    print str(track)