Commits

ont committed 2af981b

(+) reparsing magickcards.info + some corrections

  • Participants
  • Parent commits 3e7f13b

Comments (0)

Files changed (7)

 def owns_list():
     owns = list(models.Own.select().join(models.Card))
     return {'success' : True, 'data' : pw2js(owns, [
-        'id',
-        ('card',[ 'name','pict'])
+        #'when',
+        ('card',['name','pict','cost','cnum','power','tough',('cset',['name'])]),
     ])}
 
 @route('/owns', method='POST')
 def owns_add():
-    return "ADD"
+    name = request.json.get('name')
+    cset = request.json.get('cset')
+    cnt  = request.json.get('cnt')
+
+    card = models.Card.search(name, cset).get()
+    card.fetch()
+    card.save()
+
+    res = []
+    for i in xrange(cnt):
+        own = models.Own(card = card)
+        own.save()
+        res.append(own)
+
+    return {'success' : True, 'data' : pw2js(res, [
+        #'when',
+        ('card',['name','pict','cost','cnum','power','tough',('cset',['name'])]),
+    ])}
 
 
 @route('/cards')
+.mtg-cards-grid li {
+    position: relative;
+}
+
+.mtg-cards-grid li > img:last-child {
+    display: none;
+    position: absolute;
+    top: 50%;
+    left: 50%;
+    transform: translate(-50%,-50%);
+    -webkit-transform: translate(-50%,-50%);
+}
+
+.mtg-cards-grid li:hover > img:last-child {
+    display: block !important;
+    max-width: 250px;
+    margin: auto;
+    z-index: 100;
+}
 
   
   <link rel="stylesheet" href="css/foundation.css">
+  <link rel="stylesheet" href="css/mtg.css">
   
 
   <script src="js/peg-0.7.0.min.js"></script>
 
 	<div class="row">
 		<div class="large-12 columns">
-            <ul class="large-block-grid-3">
-                <li ng-repeat="card in cards"><img width="80%" ng-src="{{card.pict}}"></li>
+            <ul class="large-block-grid-6 mtg-cards-grid">
+                <li ng-repeat="own in owns | orderBy:'card.tough'">
+                    <img ng-src="{{own.card.pict}}"/>
+                    <img ng-src="{{own.card.pict}}"/>
+                </li>
             </ul>
 
 			<!-- Grid Example -->

File js/controllers.js

         console.log(cmd, prs.parse(cmd));
         res = prs.parse(cmd);
         if( res[0] == 'add' ) {
+            owns.post({'cnt': res[1], 'name': res[2][0], 'cset': res[2][1]})
+                .then(function(owns){
+                    _.each(owns, function(x){
+                        $scope.owns.push(x);
+                    });
+
+                    $scope.xxx = 'add 1 "';
+                });
         } else if( res[0] == 'del' ) {
         }
     }

File js/directives.js

                     if( !list ){
                         var cmd = scope[attrs.cmdTab];
                         var pos = cmd.lastIndexOf('"');
+                        var spaced = false;
+
+                        if( pos < 0 )
+                        {
+                            pos = cmd.lastIndexOf(' ');
+                            spaced = true;
+                        }
 
                         tail = cmd.substring(pos+1);
-                        head = cmd.substring(0,pos);
+                        head = cmd.substring(0,pos) + (spaced ? ' ' : '');
 
                         scope[attrs.cmdTabSrc](tail).then(function(data){
                             list = data;
   = add_cmd / del_cmd
  
 add_cmd
-  = act:"add"i " "* cnt:cnt? " "* names:card_name* {return [act, cnt, names]}
+  = act:"add"i " "* cnt:cnt? " "* names:card_name {return [act, cnt, names]}
  
 del_cmd
-  = act:"del"i " "* cnt:cnt? " "* name:card_name* {return [act, cnt, name]}
+  = act:"del"i " "* cnt:cnt? " "* name:card_name {return [act, cnt, name]}
  
 card_name
-  = " "* '"' name:[A-Za-z ]+ '"' " "* { return name.join("")}
+  = " "* '"' name:[A-Za-z' ]+ '|' set:[A-Za-z 0-9]+ '"' " "* { return [name.join(""), set.join("")] }
  
 cnt
   = digits:[0-9]+ {return parseInt(digits.join(""), 10)}
 from peewee import *
 from pyquery import PyQuery as pq
 
-database = SqliteDatabase('/tmp/main.db')
+database = SqliteDatabase('/tmp/db.sqlite')
 
 class SqliteModel(Model):
     class Meta:
     pict = CharField(null=True)
     murl = CharField()
 
+    cnum   = IntegerField(null=True)
     cost   = CharField(null=True)
     type   = CharField(null=True)
     rule   = TextField(null=True)
+    rare   = IntegerField(null=True)
+
     power  = CharField(null=True)
     tough  = CharField(null=True)
     legacy = CharField(null=True)
     cset = ForeignKeyField(CardSet, related_name='cards')
 
     @classmethod
-    def search( klass, name ):
-        return Card.select().where(fn.Lower(Card.name) % ('*' + name.lower() + '*')).limit(10)
+    def search( klass, name, cset = None ):
+        res = Card.select().where(fn.Lower(Card.name) % ('*' + name.lower() + '*')).limit(10)
+        if cset:
+            res = res.join(CardSet).where(CardSet.name == cset)
+        return res
 
     def fetch( self ):
         if not self.pict or not self.rule:
             d = pq(url='http://magiccards.info' + self.murl)
             self.pict = d('table:eq(3) img').attr('src')
 
-            ## take in info in form: 
-            ## Creaturerior 1+*/1+*, 5GG (7) 
+            ## take in info in form:
+            ## Creaturerior 1+*/1+*, 5GG (7)
             info = d('table:eq(3) tr:eq(0) > td:eq(1) p:eq(0)').text()
             info = ' '.join(info.split())
-            tb, cc = info.split(',')   ## tc - type and battle properties, cc - cost and converted cost
 
-            t = ' '.join( tb.split()[:-1] )
-            b = tb.split()[-1]
+            try:
+                tb, cc = info.split(',')   ## tb - type and battle properties, cc - cost and converted cost
+                t = ' '.join( tb.split()[:-1] )
+                b = tb.split()[-1]
 
-            self.type = t
-            self.power = b.split('/')[0]
-            self.tough = b.split('/')[1]
+                self.type = t
+                self.power = b.split('/')[0]
+                self.tough = b.split('/')[1]
+            except:
+                tb, cc = info, '0 (0)'
+                self.type = tb
+                self.power = '-'
+                self.tough = '-'
+
             self.cost = cc
 
             ## take rule text
 
 
 if __name__ == '__main__':
-    for c in Card.select().where(fn.Lower(Card.name) % '*mikaeus*'):
-        print c.name
-
-    exit(0)
+    skip = True
 
     d = pq(url='http://magiccards.info/sitemap.html')
     for a in d('table:eq(1) a'):
-        cs = CardSet.create(name=a.text)
-        cs.save()
-        
+        cs_name = a.text
+
+        if cs_name == 'Mirage':
+            skip = False
+
+        if skip: continue
+
+        #cs = CardSet.create(name=a.text)
+        #cs.save()
+
         url = a.get('href')
         dd = pq(url='http://magiccards.info' + url)
 
-        for a in dd('table:eq(3) tr > td:eq(1) > a'):
-            print '[%s]' % cs.name, a.text,
-            c = Card(name=a.text, murl=a.get('href'), cset=cs)
-            c.save()
-            print '... OK'
+        for tr in dd('table:eq(3) tr:gt(0)'):
+
+            #   <tr class="even">
+            # 0   <td align="right">1</td>
+            # 1   <td><a href="/ths/en/1.html">Battlewise Valor</a></td>
+            # 2   <td>Instant</td>
+            # 3   <td>1W</td>
+            # 4   <td>Common</td>
+            # 5   <td>Zack Stella</td>
+            # 6   <td><img src="http://magiccards.info/images/en.gif" alt="English" width="16" height="11" class="flag2"/> Theros</td>
+            #   </tr>
+
+            tr = pq(tr)
+            cnum = tr('td:eq(0)').text().rstrip('qwertyuiopasdfghjklzxcvbnm')  ## collection number
+            name = tr('td:eq(1) > a').text()
+            cost = tr('td:eq(3)').text()
+            rare = ['Land', 'Common', 'Uncommon', 'Rare', 'Mythic Rare', 'Special'].index(
+                tr('td:eq(4)').text().split('(')[0].strip()
+            )
+            type = tr('td:eq(2)').text()    ## get card type
+            type = ' '.join(type.split())   ## removing \r from string
+
+            tmp = type.split()[-1]
+            if '/' in tmp:
+                power = tmp.split('/')[0]
+                tough = tmp.split('/')[1]
+            else:
+                power = tough = '-'
+
+            print '[%s] <%3s> %s >>%s<< (%s) |%s| [%s/%s]' % (cs_name, cnum, name, cost, rare, type, power, tough)
+
+            sql = Card.select().join(CardSet).where((Card.name == name) & (CardSet.name == cs_name))
+
+            if sql.count() == 1:
+                c = sql.get()
+                c.cnum = cnum
+                c.cost = cost
+                c.rare = rare
+                c.type = type
+                c.power = power
+                c.tough = tough
+                c.save()
+            elif sql.count() == 0:
+                print 'errrr'
+                exit(1)