1
0
mirror of https://github.com/Toxblh/MTMR.git synced 2026-01-10 17:08:39 +00:00

fix yandex wheather, for correct lang

This commit is contained in:
Toxblh 2019-11-26 17:33:18 +03:00
parent 466c0e5f68
commit e9e5a6f739

View File

@ -16,24 +16,24 @@ class YandexWeatherBarItem: CustomButtonTouchBarItem, CLLocationManagerDelegate
private var location: CLLocation! private var location: CLLocation!
private var prevLocation: CLLocation! private var prevLocation: CLLocation!
private var manager: CLLocationManager! private var manager: CLLocationManager!
init(identifier: NSTouchBarItem.Identifier, interval: TimeInterval) { init(identifier: NSTouchBarItem.Identifier, interval: TimeInterval) {
activity = NSBackgroundActivityScheduler(identifier: "\(identifier.rawValue).updatecheck") activity = NSBackgroundActivityScheduler(identifier: "\(identifier.rawValue).updatecheck")
activity.interval = interval activity.interval = interval
super.init(identifier: identifier, title: "") super.init(identifier: identifier, title: "")
let status = CLLocationManager.authorizationStatus() let status = CLLocationManager.authorizationStatus()
if status == .restricted || status == .denied { if status == .restricted || status == .denied {
print("User permission not given") print("User permission not given")
return return
} }
if !CLLocationManager.locationServicesEnabled() { if !CLLocationManager.locationServicesEnabled() {
print("Location services not enabled") print("Location services not enabled")
return return
} }
activity.repeats = true activity.repeats = true
activity.qualityOfService = .utility activity.qualityOfService = .utility
activity.schedule { (completion: NSBackgroundActivityScheduler.CompletionHandler) in activity.schedule { (completion: NSBackgroundActivityScheduler.CompletionHandler) in
@ -41,70 +41,70 @@ class YandexWeatherBarItem: CustomButtonTouchBarItem, CLLocationManagerDelegate
completion(NSBackgroundActivityScheduler.Result.finished) completion(NSBackgroundActivityScheduler.Result.finished)
} }
updateWeather() updateWeather()
manager = CLLocationManager() manager = CLLocationManager()
manager.delegate = self manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyHundredMeters manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
manager.startUpdatingLocation() manager.startUpdatingLocation()
tapClosure = tapClosure ?? defaultTapAction tapClosure = tapClosure ?? defaultTapAction
} }
required init?(coder _: NSCoder) { required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented") fatalError("init(coder:) has not been implemented")
} }
@objc func updateWeather() { @objc func updateWeather() {
var urlRequest = URLRequest(url: URL(string: getWeatherUrl())!) var urlRequest = URLRequest(url: URL(string: getWeatherUrl())!)
urlRequest.addValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36", forHTTPHeaderField: "user-agent") // important for the right format urlRequest.addValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36", forHTTPHeaderField: "user-agent") // important for the right format
let task = URLSession.shared.dataTask(with: urlRequest) { data, _, error in let task = URLSession.shared.dataTask(with: urlRequest) { data, _, error in
guard error == nil, let response = data?.utf8string else { guard error == nil, let response = data?.utf8string else {
return return
} }
// print(response) // print(response)
var matches: [[String]] var matches: [[String]]
var temperature: String? var temperature: String?
matches = response.matchingStrings(regex: "fact__temp.*?temp__value.*?>(.*?)<") matches = response.matchingStrings(regex: "fact__temp.*?temp__value.*?>(.*?)<")
temperature = matches.first?.item(at: 1) temperature = matches.first?.item(at: 1)
var icon: String? var icon: String?
matches = response.matchingStrings(regex: "link__condition.*?>(.*?)<") matches = response.matchingStrings(regex: "link__condition.*?>(.*?)<")
icon = matches.first?.item(at: 1) icon = matches.first?.item(at: 1)
if let _ = icon, let test = self.iconsSource[icon!] { if let _ = icon, let test = self.iconsSource[icon!] {
icon = test icon = test
} }
if temperature != nil { if temperature != nil {
DispatchQueue.main.async { DispatchQueue.main.async {
self.setWeather(text: "\(icon ?? "?") \(temperature!)\(self.unitsStr)") self.setWeather(text: "\(icon ?? "?") \(temperature!)\(self.unitsStr)")
} }
} }
} }
task.resume() task.resume()
} }
func getWeatherUrl() -> String { func getWeatherUrl() -> String {
if location != nil { if location != nil {
return "https://yandex.ru/pogoda/?lat=\(location.coordinate.latitude)&lon=\(location.coordinate.longitude)" return "https://yandex.ru/pogoda/?lat=\(location.coordinate.latitude)&lon=\(location.coordinate.longitude)?lang=ru"
} else { } else {
return "https://yandex.ru/pogoda/" // Yandex will try to determine your location by default return "https://yandex.ru/pogoda/?lang=ru" // Yandex will try to determine your location by default
} }
} }
func setWeather(text: String) { func setWeather(text: String) {
title = text title = text
} }
func defaultTapAction() { func defaultTapAction() {
print(getWeatherUrl()) print(getWeatherUrl())
if let url = URL(string: getWeatherUrl()) { if let url = URL(string: getWeatherUrl()) {
NSWorkspace.shared.open(url) NSWorkspace.shared.open(url)
} }
} }
func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) { func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let lastLocation = locations.last! let lastLocation = locations.last!
location = lastLocation location = lastLocation
@ -113,15 +113,15 @@ class YandexWeatherBarItem: CustomButtonTouchBarItem, CLLocationManagerDelegate
} }
prevLocation = lastLocation prevLocation = lastLocation
} }
func locationManager(_: CLLocationManager, didFailWithError error: Error) { func locationManager(_: CLLocationManager, didFailWithError error: Error) {
print(error) print(error)
} }
func locationManager(_: CLLocationManager, didChangeAuthorization _: CLAuthorizationStatus) { func locationManager(_: CLLocationManager, didChangeAuthorization _: CLAuthorizationStatus) {
updateWeather() updateWeather()
} }
deinit { deinit {
activity.invalidate() activity.invalidate()
} }
@ -131,9 +131,9 @@ extension String {
func matchingStrings(regex: String) -> [[String]] { func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] } guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length)) let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in return results.map { result in
(0..<result.numberOfRanges).map { (0 ..< result.numberOfRanges).map {
result.range(at: $0).location != NSNotFound result.range(at: $0).location != NSNotFound
? nsString.substring(with: result.range(at: $0)) ? nsString.substring(with: result.range(at: $0))
: "" : ""