forked from fofix/fofix
/
Song.py
4492 lines (3796 loc) · 159 KB
/
Song.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire #
# Copyright (C) 2006 Sami Kyöstilä #
# 2008 myfingershurt #
# 2009 Pascal Giard #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #
# MA 02110-1301, USA. #
#####################################################################
import midi
import Log
import Audio
import Config
import os
import re
import shutil
import math
import random
import Config
#stump: when we completely drop 2.4 support, change this to just "import hashlib"
try:
import hashlib
except ImportError:
import sha
class hashlib:
sha1 = sha.sha
import binascii
import Cerealizer
import urllib
import Version
import Theme
import copy
import string
import cPickle #stump: Cerealizer and sqlite3 don't seem to like each other that much...
import Resource
import time
from Language import _
import VFS
DEFAULT_BPM = 120.0
DEFAULT_LIBRARY = "songs"
EXP_DIF = 0
HAR_DIF = 1
MED_DIF = 2
EAS_DIF = 3
#MFH - special / global text-event tracks for the separated text-event list variable
TK_SCRIPT = 0 #script.txt events
TK_SECTIONS = 1 #Section events
TK_GUITAR_SOLOS = 2 #Guitar Solo start/stop events
TK_LYRICS = 3 #RB MIDI Lyric events
TK_UNUSED_TEXT = 4 #Unused / other text events
#code for adding tracks, inside song.py:
#self.song.eventTracks[TK_SCRIPT].addEvent(self.abs_time(), event) #MFH - add an event to the script.txt track
#self.song.eventTracks[TK_SECTIONS].addEvent(self.abs_time(), event) #MFH - add an event to the sections track
#self.song.eventTracks[TK_GUITAR_SOLOS].addEvent(self.abs_time(), event) #MFH - add an event to the guitar solos track
#self.song.eventTracks[TK_LYRICS].addEvent(self.abs_time(), event) #MFH - add an event to the lyrics track
#self.song.eventTracks[TK_UNUSED_TEXT].addEvent(self.abs_time(), event) #MFH - add an event to the unused text track
#code for accessing track objects, outside song.py:
#self.song.eventTracks[Song.TK_SCRIPT]
#self.song.eventTracks[Song.TK_SECTIONS]
#self.song.eventTracks[Song.TK_GUITAR_SOLOS]
#self.song.eventTracks[Song.TK_LYRICS]
#self.song.eventTracks[Song.TK_UNUSED_TEXT]
GUITAR_TRACK = 0
RHYTHM_TRACK = 1
DRUM_TRACK = 2
#FOF_TYPE = 0
#GH1_TYPE = 1
#GH2_TYPE = 2
#MFH
MIDI_TYPE_GH = 0 #GH type MIDIs have starpower phrases marked with a long G8 note on that instrument's track
MIDI_TYPE_RB = 1 #RB type MIDIs have overdrive phrases marked with a long G#9 note on that instrument's track
MIDI_TYPE_WT = 2 #WT type MIDIs have six notes and HOPOs marked on F# of the track
#MFH
EARLY_HIT_WINDOW_NONE = 1 #GH1/RB1/RB2 = NONE
EARLY_HIT_WINDOW_HALF = 2 #GH2/GH3/GHA/GH80's = HALF
EARLY_HIT_WINDOW_FULL = 3 #FoF = FULL
GUITAR_PART = 0
RHYTHM_PART = 1
BASS_PART = 2
LEAD_PART = 3
DRUM_PART = 4
VOCAL_PART = 5
PART_SORT = [0,2,3,1,4,5] # these put Lead before Rhythm in menus.
SORT_PART = [0,3,1,2,4,5]
instrumentDiff = {
0 : (lambda a: a.diffGuitar),
1 : (lambda a: a.diffGuitar),
2 : (lambda a: a.diffBass),
3 : (lambda a: a.diffGuitar),
4 : (lambda a: a.diffDrums),
5 : (lambda a: a.diffVocals)
}
class Part:
def __init__(self, id, text):
self.id = id
self.text = text
#self.logClassInits = Config.get("game", "log_class_inits")
#if self.logClassInits == 1:
# Log.debug("Part class init (song.py)...")
def __cmp__(self, other):
if isinstance(other, Part):
return cmp(PART_SORT[self.id], PART_SORT[other.id])
else:
return cmp(self.id, other) #if it's not being compared with a part, we probably want its real ID.
def __str__(self):
return self.text
def __repr__(self):
return self.text
parts = {
GUITAR_PART: Part(GUITAR_PART, _("Guitar")),
RHYTHM_PART: Part(RHYTHM_PART, _("Rhythm")),
BASS_PART: Part(BASS_PART, _("Bass")),
LEAD_PART: Part(LEAD_PART, _("Lead")),
DRUM_PART: Part(DRUM_PART, _("Drums")),
VOCAL_PART: Part(VOCAL_PART, _("Vocals")),
}
class Difficulty:
def __init__(self, id, text):
self.id = id
self.text = text
#self.logClassInits = Config.get("game", "log_class_inits")
#if self.logClassInits == 1:
# Log.debug("Difficulty class init (song.py)...")
def __cmp__(self, other):
if isinstance(other, Difficulty):
return cmp(self.id, other.id)
else:
return cmp(self.id, other)
def __str__(self):
return self.text
def __repr__(self):
return self.text
difficulties = {
EAS_DIF: Difficulty(EAS_DIF, _("Easy")),
MED_DIF: Difficulty(MED_DIF, _("Medium")),
HAR_DIF: Difficulty(HAR_DIF, _("Hard")),
EXP_DIF: Difficulty(EXP_DIF, _("Expert")),
}
defaultSections = ["Start","1/4","1/2","3/4"]
# Load the song database and check that it is completely initialized.
_SCHEMA_VERSION = 7 #stump: current database format version number
_songDB = VFS.openSqlite3('/userdata/SongCache.sqlite')
try:
_dbversion = _songDB.execute("SELECT `value` FROM `config` WHERE `key` = 'version'").fetchone()[0]
if int(_dbversion) == 6:
Log.debug('Upgrading song cache schema version 6 to 7.')
_songDB.execute('ALTER TABLE `songinfo` ADD `seen` INT')
_songDB.execute('UPDATE `songinfo` SET `seen` = 0')
_songDB.execute("UPDATE `config` SET `value` = '7' WHERE `key` = 'version'")
_songDB.commit()
_dbversion = 7
# (Insert future schema upgrades here - with ifs, not elifs, so we are
# able to upgrade starting at *any* schema version we support
# upgrading from, like so.)
#if _dbversion == 7:
# Log.debug('Upgrading song cache schema version 7 to 8.')
# _songDB.execute(sql needed to do the update)
# _songDB.commit()
# _dbversion = 8
if _dbversion == _SCHEMA_VERSION:
_mustReinitialize = False
else:
_mustReinitialize = True
Log.debug('Song cache has incompatible schema version; forcing reinitialization.')
except:
_mustReinitialize = True
if _mustReinitialize:
Log.debug('Initializing song cache.')
# Clean out the database, then make our tables.
for tbl in _songDB.execute("SELECT `name` FROM `sqlite_master` WHERE `type` = 'table'").fetchall():
_songDB.execute('DROP TABLE `%s`' % tbl)
_songDB.execute('VACUUM')
#stump: if you need to change the database schema, do it here, then bump the version number, a small bit above here.
_songDB.execute('CREATE TABLE `config` (`key` STRING UNIQUE, `value` STRING)')
_songDB.execute('CREATE TABLE `songinfo` (`hash` STRING UNIQUE, `info` STRING, `seen` INT)')
_songDB.execute('INSERT INTO `config` (`key`, `value`) VALUES (?, ?)', ('version', _SCHEMA_VERSION))
_songDB.commit()
class SongInfo(object):
def __init__(self, infoFileName, songLibrary = DEFAULT_LIBRARY):
self.songName = os.path.basename(os.path.dirname(infoFileName))
self.fileName = infoFileName
self.libraryNam = songLibrary[:]
self.info = Config.MyConfigParser()
self._partDifficulties = {}
self._parts = None
self._midiStyle = None
self.locked = False
#MFH - want to read valid sections from the MIDI in for practice mode selection here:
self._sections = None
self.name = _("NoName")
try:
self.info.read(infoFileName)
except:
pass
self.logClassInits = Config.get("game", "log_class_inits")
if self.logClassInits == 1:
Log.debug("SongInfo class init (song.py): " + self.name)
self.logSections = Config.get("game", "log_sections")
self.logUneditedMidis = Config.get("log", "log_unedited_midis")
self.useUneditedMidis = Config.get("debug", "use_unedited_midis")
if self.useUneditedMidis == 1: #auto
#if os.path.exists(os.path.join(os.path.dirname(self.fileName), "notes-unedited.mid"))
if os.path.isfile(os.path.join(os.path.dirname(self.fileName), "notes-unedited.mid")):
notefile = "notes-unedited.mid"
if self.logUneditedMidis == 1:
Log.debug("notes-unedited.mid found, using instead of notes.mid! - " + self.name)
else:
notefile = "notes.mid"
if self.logUneditedMidis == 1:
Log.debug("notes-unedited.mid not found, using notes.mid - " + self.name)
else:
notefile = "notes.mid"
if self.logUneditedMidis == 1:
Log.debug("notes-unedited.mid not found, using notes.mid - " + self.name)
self.noteFileName = os.path.join(os.path.dirname(self.fileName), notefile)
# Read highscores and verify their hashes.
# There ain't no security like security throught obscurity :)
self.highScores = {}
scores = self._get("scores", str, "")
scores_ext = self._get("scores_ext", str, "")
if scores:
scores = Cerealizer.loads(binascii.unhexlify(scores))
if scores_ext:
scores_ext = Cerealizer.loads(binascii.unhexlify(scores_ext))
for difficulty in scores.keys():
try:
difficulty = difficulties[difficulty]
except KeyError:
continue
for i, base_scores in enumerate(scores[difficulty.id]):
score, stars, name, hash = base_scores
if scores_ext != "":
#Someone may have mixed extended and non extended
try:
if len(scores_ext[difficulty.id][i]) < 9:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, oldInfo, oldInfo2 = scores_ext[difficulty.id][i]
handicapValue = 0
longHandicap = "None"
originalScore = 0
else:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore = scores_ext[difficulty.id][i]
scoreExt = (notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore)
except:
hash_ext = 0
scoreExt = (0, 0, 0 , "RF-mod", 0, "None", 0)
if self.getScoreHash(difficulty, score, stars, name) == hash:
if scores_ext != "" and hash == hash_ext:
self.addHighscore(difficulty, score, stars, name, part = parts[GUITAR_PART], scoreExt = scoreExt)
else:
self.addHighscore(difficulty, score, stars, name, part = parts[GUITAR_PART])
else:
Log.warn("Weak hack attempt detected. Better luck next time.")
self.highScoresRhythm = {}
scores = self._get("scores_rhythm", str, "")
scores_ext = self._get("scores_rhythm_ext", str, "")
if scores:
scores = Cerealizer.loads(binascii.unhexlify(scores))
if scores_ext:
scores_ext = Cerealizer.loads(binascii.unhexlify(scores_ext))
for difficulty in scores.keys():
try:
difficulty = difficulties[difficulty]
except KeyError:
continue
#for score, stars, name, hash in scores[difficulty.id]:
# if self.getScoreHash(difficulty, score, stars, name) == hash:
# self.addHighscore(difficulty, score, stars, name, part = parts[RHYTHM_PART])
# else:
# Log.warn("Weak hack attempt detected. Better luck next time.")
for i, base_scores in enumerate(scores[difficulty.id]):
score, stars, name, hash = base_scores
if scores_ext != "":
#Someone may have mixed extended and non extended
try:
if len(scores_ext[difficulty.id][i]) < 9:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, oldInfo, oldInfo2 = scores_ext[difficulty.id][i]
handicapValue = 0
longHandicap = "None"
originalScore = 0
else:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore = scores_ext[difficulty.id][i]
scoreExt = (notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore)
except:
hash_ext = 0
scoreExt = (0, 0, 0 , "RF-mod", 0, "None", 0)
if self.getScoreHash(difficulty, score, stars, name) == hash:
if scores_ext != "" and hash == hash_ext:
self.addHighscore(difficulty, score, stars, name, part = parts[RHYTHM_PART], scoreExt = scoreExt)
else:
self.addHighscore(difficulty, score, stars, name, part = parts[RHYTHM_PART])
else:
Log.warn("Weak hack attempt detected. Better luck next time.")
self.highScoresBass = {}
scores = self._get("scores_bass", str, "")
scores_ext = self._get("scores_bass_ext", str, "")
if scores:
scores = Cerealizer.loads(binascii.unhexlify(scores))
if scores_ext:
scores_ext = Cerealizer.loads(binascii.unhexlify(scores_ext))
for difficulty in scores.keys():
try:
difficulty = difficulties[difficulty]
except KeyError:
continue
#for score, stars, name, hash in scores[difficulty.id]:
# if self.getScoreHash(difficulty, score, stars, name) == hash:
# self.addHighscore(difficulty, score, stars, name, part = parts[BASS_PART])
# else:
# Log.warn("Weak hack attempt detected. Better luck next time.")
for i, base_scores in enumerate(scores[difficulty.id]):
score, stars, name, hash = base_scores
if scores_ext != "":
#Someone may have mixed extended and non extended
try:
if len(scores_ext[difficulty.id][i]) < 9:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, oldInfo, oldInfo2 = scores_ext[difficulty.id][i]
handicapValue = 0
longHandicap = "None"
originalScore = 0
else:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore = scores_ext[difficulty.id][i]
scoreExt = (notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore)
except:
hash_ext = 0
scoreExt = (0, 0, 0 , "RF-mod", 0, "None", 0)
if self.getScoreHash(difficulty, score, stars, name) == hash:
if scores_ext != "" and hash == hash_ext:
self.addHighscore(difficulty, score, stars, name, part = parts[BASS_PART], scoreExt = scoreExt)
else:
self.addHighscore(difficulty, score, stars, name, part = parts[BASS_PART])
else:
Log.warn("Weak hack attempt detected. Better luck next time.")
self.highScoresLead = {}
scores = self._get("scores_lead", str, "")
scores_ext = self._get("scores_lead_ext", str, "")
if scores:
scores = Cerealizer.loads(binascii.unhexlify(scores))
if scores_ext:
scores_ext = Cerealizer.loads(binascii.unhexlify(scores_ext))
for difficulty in scores.keys():
try:
difficulty = difficulties[difficulty]
except KeyError:
continue
#for score, stars, name, hash in scores[difficulty.id]:
# if self.getScoreHash(difficulty, score, stars, name) == hash:
# self.addHighscore(difficulty, score, stars, name, part = parts[LEAD_PART])
# else:
# Log.warn("Weak hack attempt detected. Better luck next time.")
for i, base_scores in enumerate(scores[difficulty.id]):
score, stars, name, hash = base_scores
if scores_ext != "":
#Someone may have mixed extended and non extended
try:
if len(scores_ext[difficulty.id][i]) < 9:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, oldInfo, oldInfo2 = scores_ext[difficulty.id][i]
handicapValue = 0
longHandicap = "None"
originalScore = 0
else:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore = scores_ext[difficulty.id][i]
scoreExt = (notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore)
except:
hash_ext = 0
scoreExt = (0, 0, 0 , "RF-mod", 0, "None", 0)
if self.getScoreHash(difficulty, score, stars, name) == hash:
if scores_ext != "" and hash == hash_ext:
self.addHighscore(difficulty, score, stars, name, part = parts[LEAD_PART], scoreExt = scoreExt)
else:
self.addHighscore(difficulty, score, stars, name, part = parts[LEAD_PART])
else:
Log.warn("Weak hack attempt detected. Better luck next time.")
#myfingershurt: drums :)
self.highScoresDrum = {}
scores = self._get("scores_drum", str, "")
scores_ext = self._get("scores_drum_ext", str, "")
if scores:
scores = Cerealizer.loads(binascii.unhexlify(scores))
if scores_ext:
scores_ext = Cerealizer.loads(binascii.unhexlify(scores_ext))
for difficulty in scores.keys():
try:
difficulty = difficulties[difficulty]
except KeyError:
continue
#for score, stars, name, hash in scores[difficulty.id]:
# if self.getScoreHash(difficulty, score, stars, name) == hash:
# self.addHighscore(difficulty, score, stars, name, part = parts[DRUM_PART])
# else:
# Log.warn("Weak hack attempt detected. Better luck next time.")
for i, base_scores in enumerate(scores[difficulty.id]):
score, stars, name, hash = base_scores
if scores_ext != "":
#Someone may have mixed extended and non extended
try:
if len(scores_ext[difficulty.id][i]) < 9:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, oldInfo, oldInfo2 = scores_ext[difficulty.id][i]
handicapValue = 0
longHandicap = "None"
originalScore = 0
else:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore = scores_ext[difficulty.id][i]
scoreExt = (notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore)
except:
hash_ext = 0
scoreExt = (0, 0, 0 , "RF-mod", 0, "None", 0)
if self.getScoreHash(difficulty, score, stars, name) == hash:
if scores_ext != "" and hash == hash_ext:
self.addHighscore(difficulty, score, stars, name, part = parts[DRUM_PART], scoreExt = scoreExt)
else:
self.addHighscore(difficulty, score, stars, name, part = parts[DRUM_PART])
else:
Log.warn("Weak hack attempt detected. Better luck next time.")
#akedrou - vocals!
self.highScoresVocal = {}
scores = self._get("scores_vocal", str, "")
scores_ext = self._get("scores_vocal_ext", str, "")
if scores:
scores = Cerealizer.loads(binascii.unhexlify(scores))
if scores_ext:
scores_ext = Cerealizer.loads(binascii.unhexlify(scores_ext))
for difficulty in scores.keys():
try:
difficulty = difficulties[difficulty]
except KeyError:
continue
#for score, stars, name, hash in scores[difficulty.id]:
# if self.getScoreHash(difficulty, score, stars, name) == hash:
# self.addHighscore(difficulty, score, stars, name, part = parts[DRUM_PART])
# else:
# Log.warn("Weak hack attempt detected. Better luck next time.")
for i, base_scores in enumerate(scores[difficulty.id]):
score, stars, name, hash = base_scores
if scores_ext != "":
#Someone may have mixed extended and non extended
try:
if len(scores_ext[difficulty.id][i]) < 9:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, oldInfo, oldInfo2 = scores_ext[difficulty.id][i]
handicapValue = 0
longHandicap = "None"
originalScore = 0
else:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore = scores_ext[difficulty.id][i]
scoreExt = (notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore)
except:
hash_ext = 0
scoreExt = (0, 0, 0 , "RF-mod", 0, "None", 0)
if self.getScoreHash(difficulty, score, stars, name) == hash:
if scores_ext != "" and hash == hash_ext:
self.addHighscore(difficulty, score, stars, name, part = parts[DRUM_PART], scoreExt = scoreExt)
else:
self.addHighscore(difficulty, score, stars, name, part = parts[DRUM_PART])
else:
Log.warn("Weak hack attempt detected. Better luck next time.")
#stump: metadata caching
if Config.get("performance", "cache_song_metadata"):
songhash = hashlib.sha1(open(self.noteFileName, 'rb').read()).hexdigest()
try: #MFH - it crashes here on previews!
result = _songDB.execute('SELECT `info` FROM `songinfo` WHERE `hash` = ?', [songhash]).fetchone()
if result is None:
Log.debug('Song %s was not found in the cache.' % infoFileName)
except Exception, e:
Log.error('Cache retrieval failed for %s: ' % infoFileName)
result = None
if result is not None:
try:
self.__dict__.update(cPickle.loads(str(result[0])))
_songDB.execute('UPDATE `songinfo` SET `seen` = 1 WHERE `hash` = ?', [songhash])
Log.debug('Song %s successfully loaded from cache.' % infoFileName)
return
except:
# The entry is there but could not be loaded.
# Nuke it and let it be rebuilt.
Log.error('Song %s has invalid cache data (will rebuild): ' % infoFileName)
_songDB.execute('DELETE FROM `songinfo` WHERE `hash` = ?', [songhash])
#stump: preload this stuff...
self.getParts()
self.getSections()
#stump: Write this song's info into the cache.
Log.debug('Writing out cache for song %s.' % self.fileName)
pdict = {}
for key in ('_parts', '_partDifficulties', '_midiStyle', '_sections'):
pdict[key] = getattr(self, key)
_songDB.execute('INSERT OR REPLACE INTO `songinfo` (`hash`, `info`, `seen`) VALUES (?, ?, 1)', [songhash, cPickle.dumps(pdict)])
def _set(self, attr, value):
if not self.info.has_section("song"):
self.info.add_section("song")
if type(value) == unicode:
value = value.encode(Config.encoding)
else:
value = str(value)
self.info.set("song", attr, value)
def getObfuscatedScores(self, part = parts[GUITAR_PART]):
s = {}
if part == parts[GUITAR_PART]:
highScores = self.highScores
elif part == parts[RHYTHM_PART]:
highScores = self.highScoresRhythm
elif part == parts[BASS_PART]:
highScores = self.highScoresBass
elif part == parts[LEAD_PART]:
highScores = self.highScoresLead
elif part == parts[DRUM_PART]:
highScores = self.highScoresDrum
elif part == parts[VOCAL_PART]:
highScores = self.highScoresVocal
else:
highScores = self.highScores
for difficulty in highScores.keys():
if isinstance(difficulty, Difficulty):
diff = diff.id
else:
diff = difficulty
s[diff] = [(score, stars, name, self.getScoreHash(difficulty, score, stars, name)) for score, stars, name, scores_ext in highScores[difficulty]]
return binascii.hexlify(Cerealizer.dumps(s))
def getObfuscatedScoresExt(self, part = parts[GUITAR_PART]):
s = {}
if part == parts[GUITAR_PART]:
highScores = self.highScores
elif part == parts[RHYTHM_PART]:
highScores = self.highScoresRhythm
elif part == parts[BASS_PART]:
highScores = self.highScoresBass
elif part == parts[LEAD_PART]:
highScores = self.highScoresLead
elif part == parts[DRUM_PART]:
highScores = self.highScoresDrum
elif part == parts[VOCAL_PART]:
highScores = self.highScoresVocal
else:
highScores = self.highScores
for difficulty in highScores.keys():
if isinstance(difficulty, Difficulty):
diff = diff.id
else:
diff = difficulty
s[diff] = [(self.getScoreHash(difficulty, score, stars, name), stars) + scores_ext for score, stars, name, scores_ext in highScores[difficulty]]
return binascii.hexlify(Cerealizer.dumps(s))
def save(self):
if self.highScores != {}:
self._set("scores", self.getObfuscatedScores(part = parts[GUITAR_PART]))
self._set("scores_ext", self.getObfuscatedScoresExt(part = parts[GUITAR_PART]))
if self.highScoresRhythm != {}:
self._set("scores_rhythm", self.getObfuscatedScores(part = parts[RHYTHM_PART]))
self._set("scores_rhythm_ext", self.getObfuscatedScoresExt(part = parts[RHYTHM_PART]))
if self.highScoresBass != {}:
self._set("scores_bass", self.getObfuscatedScores(part = parts[BASS_PART]))
self._set("scores_bass_ext", self.getObfuscatedScoresExt(part = parts[BASS_PART]))
if self.highScoresLead != {}:
self._set("scores_lead", self.getObfuscatedScores(part = parts[LEAD_PART]))
self._set("scores_lead_ext", self.getObfuscatedScoresExt(part = parts[LEAD_PART]))
#myfingershurt: drums :)
if self.highScoresDrum != {}:
self._set("scores_drum", self.getObfuscatedScores(part = parts[DRUM_PART]))
self._set("scores_drum_ext", self.getObfuscatedScoresExt(part = parts[DRUM_PART]))
#akedrou
if self.highScoresVocal != {}:
self._set("scores_vocal", self.getObfuscatedScores(part = parts[VOCAL_PART]))
self._set("scores_vocal_ext", self.getObfuscatedScoresExt(part = parts[VOCAL_PART]))
if os.access(os.path.dirname(self.fileName), os.W_OK) == True:
f = open(self.fileName, "w")
self.info.write(f)
f.close()
def _get(self, attr, type = None, default = ""):
try:
v = self.info.get("song", attr)
except:
v = default
if v == "": #key found, but empty - need to catch as int("") will burn.
v = default
if v is not None and type:
v = type(v)
return v
def getPartDifficulties(self):
if len(self._partDifficulties) != 0:
return self._partDifficulties
self.getParts()
return self._partDifficulties
partDifficulties = property(getPartDifficulties)
def getMidiStyle(self):
if self._midiStyle is not None:
return self._midiStyle
self.getParts()
return self._midiStyle
midiStyle = property(getMidiStyle)
def getParts(self):
if self._parts is not None:
return self._parts
# See which parts are available
try:
noteFileName = self.noteFileName
Log.debug("Retrieving parts from: " + noteFileName)
info = MidiPartsDiffReader()
midiIn = midi.MidiInFile(info, noteFileName)
midiIn.read()
if info.parts == []:
Log.debug("Improperly named tracks. Attempting to force first track guitar.")
info = MidiPartsDiffReader(forceGuitar = True)
midiIn = midi.MidiInFile(info, noteFileName)
midiIn.read()
if info.parts == []:
Log.warn("No tracks found!")
raise Exception
self._midiStyle = info.midiStyle
info.parts.sort(lambda b, a: cmp(b.id, a.id))
self._parts = info.parts
for part in info.parts:
if self.tutorial:
self._partDifficulties[part.id] = [difficulties[HAR_DIF]]
continue
info.difficulties[part.id].sort(lambda a, b: cmp(a.id, b.id))
self._partDifficulties[part.id] = info.difficulties[part.id]
except:
Log.warn("Note file not parsed correctly. Selected part and/or difficulty may not be available.")
self._parts = parts.values()
for part in self._parts:
self._partDifficulties[part.id] = difficulties.values()
return self._parts
def getName(self):
return self._get("name")
def setName(self, value):
self._set("name", value)
@property
def artist(self):
return self._get("artist")
@property
def album(self):
return self._get("album")
@property
def genre(self):
return self._get("genre")
@property
def icon(self):
return self._get("icon")
@property
def bossBattle(self):
return self._get("boss_battle")
@property
def diffSong(self):
return self._get("diff_band", int, -1)
@property
def diffGuitar(self):
return self._get("diff_guitar", int, -1)
@property
def diffDrums(self):
return self._get("diff_drums", int, -1)
@property
def diffBass(self):
return self._get("diff_bass", int, -1)
@property
def diffVocals(self):
return self._get("diff_vocals", int, -1)
@property
def year(self):
return self._get("year")
@property
def loadingPhrase(self):
return self._get("loading_phrase")
@property
def cassetteColor(self):
c = self._get("cassettecolor")
if c:
return Theme.Theme.hexToColor(c)
def getScoreHash(self, difficulty, score, stars, name):
if isinstance(difficulty, Difficulty):
difficulty = difficulty.id
return hashlib.sha1("%d%d%d%s" % (difficulty, score, stars, name)).hexdigest()
@property
def delay(self):
return self._get("delay", int, 0)
@property
def frets(self):
return self._get("frets")
@property
def version(self):
return self._get("version")
@property
def tags(self):
return self._get("tags")
@property
def hopo(self):
return self._get("hopo")
def getCount(self):
return self._get("count")
def setCount(self, value):
self._set("count", value)
@property
def eighthNoteHopo(self):
return self._get("eighthnote_hopo")
@property
def lyrics(self):
return self._get("lyrics")
@property
def video(self):
return self._get("video")
@property
def video_start_time(self):
return self._get("video_start_time", int, 0)
@property
def video_end_time(self):
return self._get("video_end_time", int, -1)
def getHighscoresWithPartString(self, difficulty, part = str(parts[GUITAR_PART]) ):
if part == str(parts[GUITAR_PART]):
highScores = self.highScores
elif part == str(parts[RHYTHM_PART]):
highScores = self.highScoresRhythm
elif part == str(parts[BASS_PART]):
highScores = self.highScoresBass
elif part == str(parts[LEAD_PART]):
highScores = self.highScoresLead
#myfingershurt: drums :)
elif part == str(parts[DRUM_PART]):
highScores = self.highScoresDrum
elif part == str(parts[VOCAL_PART]): #akedrou - vocals!
highScores = self.highScoresVocal
else:
highScores = self.highScores
try:
return highScores[difficulty.id]
except KeyError:
return []
def getHighscores(self, difficulty, part = parts[GUITAR_PART]):
if part == parts[GUITAR_PART]:
highScores = self.highScores
elif part == parts[RHYTHM_PART]:
highScores = self.highScoresRhythm
elif part == parts[BASS_PART]:
highScores = self.highScoresBass
elif part == parts[LEAD_PART]:
highScores = self.highScoresLead
#myfingershurt: drums :)
elif part == parts[DRUM_PART]:
highScores = self.highScoresDrum
elif part == parts[VOCAL_PART]: #akedrou - vocals!
highScores = self.highScoresVocal
else:
highScores = self.highScores
try:
return highScores[difficulty.id]
except KeyError:
return []
def uploadHighscores(self, url, songHash, part = parts[GUITAR_PART]):
if part == parts[VOCAL_PART]: #not implemented
return False
try:
d = {
"songName": self.songName,
"songHash": songHash,
"scores": self.getObfuscatedScores(part = part),
"scores_ext": self.getObfuscatedScoresExt(part = part),
"version": "%s-3.100" % Version.PROGRAM_NAME,
"songPart": part
}
data = urllib.urlopen(url + "?" + urllib.urlencode(d)).read()
Log.debug("Score upload result: %s" % data)
#return data == "True"
return data #MFH - want to return the actual result data.
except Exception, e:
Log.error("Score upload error: %s" % e)
return False
return True
def addHighscore(self, difficulty, score, stars, name, part = parts[GUITAR_PART], scoreExt = (0, 0, 0, "RF-mod", 0, "None", 0)):
if part == parts[GUITAR_PART]:
highScores = self.highScores
elif part == parts[RHYTHM_PART]:
highScores = self.highScoresRhythm
elif part == parts[BASS_PART]:
highScores = self.highScoresBass
elif part == parts[LEAD_PART]:
highScores = self.highScoresLead
#myfingershurt: drums :)
elif part == parts[DRUM_PART]:
highScores = self.highScoresDrum
elif part == parts[VOCAL_PART]: #akedrou - vocals!
highScores = self.highScoresVocal
else:
highScores = self.highScores
if not difficulty.id in highScores:
highScores[difficulty.id] = []
highScores[difficulty.id].append((score, stars, name, scoreExt))
highScores[difficulty.id].sort(lambda a, b: {True: -1, False: 1}[a[0] > b[0]])
highScores[difficulty.id] = highScores[difficulty.id][:5]
for i, scores in enumerate(highScores[difficulty.id]):
_score, _stars, _name, _scores_ext = scores
if _score == score and _stars == stars and _name == name:
return i
return -1
@property
def tutorial(self):
return self._get("tutorial", int, 0) == 1
def findTag(self, find, value = None):
for tag in self.tags.split(','):
temp = tag.split('=')
if find == temp[0]:
if value == None:
return True
elif len(temp) == 2 and value == temp[1]:
return True
return False
def getSections(self): #MFH
if self._sections is not None:
return self._sections
# See which sections are available
try:
noteFileName = self.noteFileName
Log.debug("Retrieving sections from: " + noteFileName)
info = MidiSectionReader()
midiIn = midi.MidiInFile(info, noteFileName)
try:
midiIn.read()
except MidiSectionReader.Done:
pass
self._sections = info.sections
if len(self._sections) <= 1:
self._sections = info.noteCountSections
self._sections.insert(0,["0:00 -> Start", 0.0])
#MFH - only log if enabled
Log.warn("Song.py: Using auto-generated note count sections...")
if self.logSections == 1:
Log.debug("Practice sections: " + str(self._sections))
else:
self._sections.insert(0,["0:00 -> Start", 0.0])
#MFH - only log if enabled
if self.logSections == 1:
Log.debug("Practice sections: " + str(self._sections))
except Exception, e:
Log.warn("Song.py: Unable to retrieve section names for practice mode selection: %s" % e)
self._sections = None
return self._sections
#coolguy567's unlock system
def getUnlockID(self):
return self._get("unlock_id")
def getUnlockRequire(self):
return self._get("unlock_require")
def getUnlockText(self):
return self._get("unlock_text", default = _("This song is locked."))
# This takes True or False, not the value in the ini
def setCompleted(self, value):
if value:
self._set("unlock_completed", len(removeSongOrderPrefixFromName(self.name)) * len(self.artist) + 1)
else:
self._set("unlock_completed", 0)
# This returns True or False, not the value in the ini
def getCompleted(self):
iniValue = self._get("unlock_completed", int, default = 0)
if iniValue == len(removeSongOrderPrefixFromName(self.name)) * len(self.artist) + 1: # yay, security through obscurity!
return True
else:
return False
def setLocked(self, value):
self.locked = value
# WARNING this will only work on a SongInfo loaded via getAvailableSongs
# (yeah, I know)
def getLocked(self):
return self.locked
#MFH - adding song.ini setting to allow fretter to specify early hit window size (none, half, or full)
@property
def early_hit_window_size(self): #MFH
return self._get("early_hit_window_size", str)