Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

#! /usr/bin/env python3 

# -*- coding: utf-8 -*- 

 

#       Copyright 2012, Marten de Vries 

# 

#       This file is part of OpenTeacher. 

# 

#       OpenTeacher 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 3 of the License, or 

#       (at your option) any later version. 

# 

#       OpenTeacher 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 OpenTeacher.  If not, see <http://www.gnu.org/licenses/>. 

 

import urllib.parse 

import urllib.request 

import urllib.error 

import json 

import re 

import logging 

import contextlib 

 

logger = logging.getLogger(__name__) 

 

class StudyStackApi: 

        def __init__(self, parse, *args, **kwargs): 

                super().__init__(*args, **kwargs) 

 

                self._parse = parse 

 

        def _get(self, action, **kwargs): 

                kwargs.update({ 

                        "strict": "Y", 

                        "appId": "osrc5103", 

                }) 

                url = "http://www.studystack.com/servlet/%s?%s" % ( 

                        action, 

                        urllib.parse.urlencode(kwargs) 

                ) 

                data = urllib.request.urlopen(url).read().decode('UTF-8') 

                #the JSON is escaped in an invalid way. This should fix it 

                #(every slash other than in '\"' and '\\' is removed, conform 

                #the JSON spec). 

                data = re.sub( 

                        r'("[^"]*)\\([^"\\])', 

                        r'\1\2', 

                        data 

                ) 

                return json.loads(data) 

 

        def getCategories(self): 

                categories = self._get("categoryListJson") 

                return ((c["name"], c["id"]) for c in categories) 

 

        def getLists(self, categoryId): 

                stacks = self._get("categoryStackListJson", page=1, sortOrder="stars", categoryId=categoryId) 

                stacks += self._get("categoryStackListJson", page=2, sortOrder="stars", categoryId=categoryId) 

                return ((s["stackName"], s["id"]) for s in stacks) 

 

        def getList(self, listId): 

                stack = self._get("json", studyStackId=listId) 

                items = [] 

                for i, row in enumerate(stack["data"]): 

                        items.append({ 

                                "id": i, 

                                "questions": self._parse(row[0]), 

                                "answers": self._parse(row[1]), 

                        }) 

                return { 

                        "list": { 

                                "title": stack["name"], 

                                "items": items, 

                        }, 

                        "resources": {}, 

                } 

 

def installQtClasses(): 

        global AbstractSelectDialog, BookSelectDialog, CategorySelectDialog, ListSelectDialog, Model 

 

        class Model(QtCore.QAbstractListModel): 

                def __init__(self, choices, *args, **kwargs): 

                        """Choices should be an iterable object of tuples of size two, 

                           with in it first the text to display and second the value to 

                           return. 

 

                        """ 

                        super().__init__(*args, **kwargs) 

 

                        self._choices = list(choices) 

 

                def rowCount(self, parent): 

                        return len(self._choices) 

 

                def data(self, index, role): 

                        if not (index.isValid() and role == QtCore.Qt.DisplayRole): 

                                return 

 

                        return self._choices[index.row()][0] 

 

                def getChoice(self, index): 

                        return self._choices[index.row()][1] 

 

        class AbstractSelectDialog(QtWidgets.QDialog): 

                def __init__(self, choices, *args, **kwargs): 

                        super().__init__(*args, **kwargs) 

 

                        self.label = QtWidgets.QLabel() 

 

                        self._listView = QtWidgets.QListView() 

                        self._model = Model(choices) 

                        self._listView.setModel(self._model) 

119                        if not self.singleOnly: 

                                self._listView.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) 

                        self._listView.doubleClicked.connect(self.accept) 

 

                        buttonBox = QtWidgets.QDialogButtonBox( 

                                QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok, 

                                parent=self 

                        ) 

                        buttonBox.accepted.connect(self.accept) 

                        buttonBox.rejected.connect(self.reject) 

 

                        l = QtWidgets.QVBoxLayout() 

                        l.addWidget(self.label) 

                        l.addWidget(self._listView) 

                        l.addWidget(buttonBox) 

                        self.setLayout(l) 

 

                @property 

                def chosenItems(self): 

                        return [self._model.getChoice(i) for i in self._listView.selectedIndexes()] 

 

        class CategorySelectDialog(AbstractSelectDialog): 

                singleOnly = True 

                def retranslate(self): 

                        self.setWindowTitle(_("Select category")) 

                        self.label.setText(_("Please select a category")) 

 

        class ListSelectDialog(AbstractSelectDialog): 

                singleOnly = False 

                def retranslate(self): 

                        self.setWindowTitle(_("Select list")) 

                        self.label.setText(_("Please select a list")) 

 

class StudyStackApiModule: 

        def __init__(self, moduleManager, *args, **kwargs): 

                super().__init__(*args, **kwargs) 

                self._mm = moduleManager 

 

                self.type = "studyStackApi" 

                self.requires = ( 

                        self._mm.mods(type="ui"), 

                        self._mm.mods(type="buttonRegister"), 

                        self._mm.mods(type="wordsStringParser"), 

                        self._mm.mods(type="loaderGui"), 

                ) 

                self.uses = ( 

                        self._mm.mods(type="translator"), 

                ) 

                self.filesWithTranslations = ("studyStackApi.py",) 

 

                x = 600 

                self.priorities = { 

                        "all": x, 

                        "selfstudy": x, 

                        "student@home": x, 

                        "student@school": x, 

                        "teacher": x, 

                        "words-only": x, 

                        "code-documentation": x, 

                        "test-suite": x, 

                        "default": -1, 

                } 

 

        def enable(self): 

                global QtCore, QtWidgets 

                try: 

                        from PyQt5 import QtCore, QtWidgets 

                except ImportError: 

                        return 

                installQtClasses() 

 

                self._modules = set(self._mm.mods(type="modules")).pop() 

                self._uiModule = self._modules.default("active", type="ui") 

                self._buttonRegister = self._modules.default("active", type="buttonRegister") 

 

                self._activeDialogs = set() 

 

                self._button = self._buttonRegister.registerButton("load-from-internet") 

                self._button.clicked.handle(self._selectCategory) 

                self._button.changePriority.send(self.priorities["all"]) 

 

                try: 

                        translator = self._modules.default("active", type="translator") 

                except IndexError: 

                        pass 

                else: 

                        translator.languageChanged.handle(self._retranslate) 

                self._retranslate() 

 

                self._api = StudyStackApi(self._parse) 

 

                self.active = True 

 

        def _retranslate(self): 

                global _ 

                global ngettext 

 

                #Install translator 

                try: 

                        translator = self._modules.default("active", type="translator") 

                except IndexError: 

                        _, ngettext = str, lambda a, b, n: a if n == 1 else b 

                else: 

                        _, ngettext = translator.gettextFunctions( 

                                self._mm.resourcePath("translations") 

                        ) 

 

                self._button.changeText.send(_("Import from studystack.com")) 

 

                #Translate all active dialogs 

                for dialog in self._activeDialogs: 

                        dialog.retranslate() 

                        dialog.tab.title = dialog.windowTitle() 

 

        @property 

        def _parse(self): 

                return self._modules.default("active", type="wordsStringParser").parse 

 

        def _showDialog(self, dialog): 

                tab = self._uiModule.addCustomTab(dialog) 

                tab.closeRequested.handle(tab.close) 

                dialog.rejected.connect(tab.close) 

                dialog.accepted.connect(tab.close) 

                dialog.tab = tab 

                self._activeDialogs.add(dialog) 

 

                self._retranslate() 

exit                dialog.finished.connect(lambda: self._activeDialogs.remove(dialog)) 

 

                return dialog 

 

        def _selectCategory(self): 

                with self._handlingWebErrors(): 

                        d = self._showDialog(CategorySelectDialog(self._api.getCategories())) 

exit                        d.accepted.connect(lambda: self._selectList(d)) 

 

        def _selectList(self, dialog): 

                categoryId = dialog.chosenItems[0] 

                with self._handlingWebErrors(): 

                        d = self._showDialog(ListSelectDialog(self._api.getLists(categoryId))) 

                        d.accepted.connect(lambda: self._loadSelectedLists(d)) 

 

        def _loadSelectedLists(self, dialog): 

                with self._handlingWebErrors(): 

                        for listId in dialog.chosenItems: 

                                list = self._api.getList(listId) 

                                try: 

                                        self._loadList(list) 

                                except NotImplementedError: 

                                        return 

 

                        #everything went well 

                        self._uiModule.statusViewer.show(_("The word list was imported from Study Stack successfully.")) 

 

        @contextlib.contextmanager 

        def _handlingWebErrors(self): 

                try: 

                        yield 

                except urllib.error.URLError as e: 

                        #for debugging purposes 

                        logger.debug(e, exc_info=True) 

                        QtWidgets.QMessageBox.warning( 

                                self._uiModule.qtParent, 

                                _("No Study Stack connection"), 

                                _("Study Stack didn't accept the connection. Are you sure that your internet connection works and http://www.studystack.com/ is online?") 

                        ) 

 

        def _loadList(self, list): 

                self._modules.default("active", type="loaderGui").loadFromLesson("words", list) 

 

        def disable(self): 

                self.active = False 

 

                self._buttonRegister.unregisterButton(self._button) 

 

                del self._modules 

                del self._uiModule 

                del self._buttonRegister 

 

                del self._activeDialogs 

                del self._button 

                del self._api 

 

def init(moduleManager): 

        return StudyStackApiModule(moduleManager)