Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply referral code #24

Open
wants to merge 10 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Telegram/Telegram-iOS/en.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -7209,8 +7209,10 @@ Sorry for the inconvenience.";

"ChatSettings.StickersAndReactions" = "Stickers and Emoji";
"WEV.ShareAndEarn" = "Share to Earn";
"WEV.Reward" = "Rewards";
"WEV.WatchLater" = "Watch Later";

"WEV.Subscribe" = "Subscribed";
"WEV.ApplyReferral" = "Apply Referral Code";
"Localization.TranslateMessages" = "Translate Messages";
"Localization.ShowTranslate" = "Show Translate Button";
"Localization.ShowTranslateInfo" = "Show a 'Translate' button in the message action menu.";
Expand Down
82 changes: 82 additions & 0 deletions submodules/ContactListUI/Sources/Model/WEVSubscribeActivity.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//
// WEVSubscribeActivity.swift
// _idx_ContactListUI_AE77A1D0_ios_min13.0
//
// Created by Apple on 11/11/22.
//

import Foundation
// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let projectRegionCrews = try? newJSONDecoder().decode(ProjectRegionCrews.self, from: jsonData)

import Foundation

// MARK: - ProjectRegionCrews
struct WEVSubscribeActivity: Codable {
let kind, etag: String
let items: [Item]
let nextPageToken: String
let pageInfo: PageInfo
}

// MARK: - Item
struct Item: Codable {
let kind, etag, id: String
let snippet: Snippet
let contentDetails: ContentDetails
}

// MARK: - ContentDetails
struct ContentDetails: Codable {
let upload: Upload
}

// MARK: - Upload
struct Upload: Codable {
let videoID: String

enum CodingKeys: String, CodingKey {
case videoID = "videoId"
}
}

// MARK: - Snippet
struct Snippet: Codable {
let publishedAt: Date
let channelID, title, snippetDescription: String
let thumbnails: Thumbnails
let type: String

enum CodingKeys: String, CodingKey {
case publishedAt
case channelID = "channelId"
case title
case snippetDescription = "description"
case thumbnails, type
}
}

// MARK: - Thumbnails
struct Thumbnails: Codable {
let thumbnailsDefault, medium, high: Default
let standard: Default?
let maxres: Default?

enum CodingKeys: String, CodingKey {
case thumbnailsDefault = "default"
case medium, high, standard, maxres
}
}

// MARK: - Default
struct Default: Codable {
let url: String
let width, height: Int
}

// MARK: - PageInfo
struct PageInfo: Codable {
let totalResults, resultsPerPage: Int
}
86 changes: 86 additions & 0 deletions submodules/ContactListUI/Sources/Model/WEVUser.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
//
// WEVChannel.swift
// _idx_ContactListUI_1D7887AF_ios_min13.0
//
// Created by Apple on 15/09/22.
//

import Foundation
import UIKit

// MARK: - Crew
struct WevUser: Codable {
let userId: Int64
let firstname: String?
let lastname: String?
let username: String?
let phone: String?
let referralcode: String?

enum CodingKeys: String, CodingKey {
case userId = "user_id"
case firstname = "first_name"
case lastname = "last_name"
case username = "username"
case phone = "phone"
case referralcode = "referral_code"
}
}
/**
* Generate a random referral code
*/
class referalCode {
static let digits = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
];

static let letters = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
];

static func generateRefferalCode() -> String {
var code = ""
for _ in 0..<4 {
code += letters.randomElement() ?? ""
}
for _ in 0..<1 {
code += digits.randomElement() ?? ""
}
return code
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func saveSubscribedVideoList(_ videowatchList: [SubscribedVideo]) {
UserDefaults.standard.set(data, forKey: KeySubsribeForUserDefaults)
}

func fetchWatchList() -> [SubscribedVideo] {
func fetchSubscribedList() -> [SubscribedVideo] {
guard let encodedData = UserDefaults.standard.array(forKey: KeySubsribeForUserDefaults) as? [Data] else {
return []
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,9 +256,15 @@ class WEVDiscoverSearchBar: UIView {
guard let presentationData = self.presentationData else {
return
}
textField.backgroundColor = presentationData.theme.chatList.backgroundColor
textField.textColor = presentationData.theme.list.itemPrimaryTextColor
textField.textColor = presentationData.theme.rootController.navigationSearchBar.inputPlaceholderTextColor //presentationData.theme.list.itemPrimaryTextColor
textField.tintColor = presentationData.theme.rootController.tabBar.selectedIconColor
//self.theme?.rootController.navigationBar.opaqueBackgroundColor ?? .clear
let fillColor = presentationData.theme.rootController.navigationSearchBar.inputFillColor
/*if fillColor.distance(to: presentationData.theme.list.blocksBackgroundColor) < 100 {
fillColor = fillColor.withMultipliedBrightnessBy(1.0)
}*/
textField.backgroundColor = fillColor
filterButton.backgroundColor = fillColor
cancelSearchButton.setTitleColor(presentationData.theme.rootController.tabBar.selectedIconColor, for: .normal)
}
/// 筛选按键
Expand Down Expand Up @@ -341,8 +347,9 @@ class WEVDiscoverSearchBar: UIView {
/// 筛选按键
private lazy var filterButton: UIButton = {
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "discover_search_filter"), for: .normal)
button.setImage(UIImage.init(named: "RSS_Feed"), for: .normal)
button.addTarget(self, action: #selector(filterButtonAction), for: .touchUpInside)
button.layer.cornerRadius = 5
return button
}()

Expand All @@ -357,12 +364,12 @@ class WEVDiscoverSearchBar: UIView {
}()

private func initView() {
/*addSubview(filterButton)
addSubview(filterButton)
filterButton.snp.makeConstraints { (make) in
make.right.equalToSuperview().offset(-10)
make.size.equalTo(CGSize(width: 40, height: 40))
make.centerY.equalToSuperview()
}*/
}

addSubview(cancelSearchButton)
cancelSearchButton.snp.makeConstraints { (make) in
Expand All @@ -374,7 +381,7 @@ class WEVDiscoverSearchBar: UIView {
addSubview(textField)
textField.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(10)
make.right.equalToSuperview().offset(-10)
make.right.equalToSuperview().offset(-60)
make.centerY.equalToSuperview()
make.height.equalTo(40)
}
Expand All @@ -391,7 +398,7 @@ class WEVDiscoverSearchBar: UIView {
cancelSearchButton.isHidden = true
filterButton.isHidden = false
textField.snp.updateConstraints { (make) in
make.right.equalToSuperview().offset(-10)
make.right.equalToSuperview().offset(-60)
}
case .searching, .searchCompleted:
cancelSearchButton.isHidden = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ public class WEVDiscoverRootNode: ASDisplayNode {
var arrWatchLater: [WatchLaterVideo] = []
var arrSubscribedVideos: [SubscribedVideo] = []

private let supabaseUrl = LJConfig.SupabaseKeys.supabaseUrl
private let supabaseKey = LJConfig.SupabaseKeys.supabaseKey
private let supabaseUrl = LJConfig.SupabaseKeys.supabaseUrlDev
private let supabaseKey = LJConfig.SupabaseKeys.supabaseKeyDev

/// 根据状态返回该显示的视频
private var showDataArray: [WEVVideoModel] {
Expand Down Expand Up @@ -205,7 +205,7 @@ public class WEVDiscoverRootNode: ASDisplayNode {
view.presentationData = self.presentationData
view.filterAction = {[weak self] in
guard let self = self else {return}
let vc = WEVDiscoverFilterViewController(allChannel: WEVChannel.allCases, selectedArray: self.selectedChannelArray)
/*let vc = WEVDiscoverFilterViewController(allChannel: WEVChannel.allCases, selectedArray: self.selectedChannelArray)
vc.selectedArray = self.selectedChannelArray
vc.didSelected = {[weak self] channelArray in
guard let self = self else {return}
Expand All @@ -225,8 +225,23 @@ public class WEVDiscoverRootNode: ASDisplayNode {
//fetch filter data
self.selectedChannelArray = channelArray
self.scrollViewLoadData(isHeadRefesh: true)
}*/
let push: (ViewController) -> Void = { [weak self] c in
guard let strongSelf = self, let navigationController = strongSelf.controller?.navigationController as? NavigationController else {
return
}
var updatedControllers = navigationController.viewControllers
for controller in navigationController.viewControllers.reversed() {
if controller !== strongSelf && !(controller is TabBarController) {
updatedControllers.removeLast()
} else {
break
}
}
updatedControllers.append(c)
navigationController.setViewControllers(updatedControllers, animated: true)
}
self.controller.present(vc, animated: true, completion: nil)
push(WEVSubscribeController(context: self.context))
}

view.cancelAction = {[weak self] in
Expand Down Expand Up @@ -558,7 +573,20 @@ public class WEVDiscoverRootNode: ASDisplayNode {
})

self.backgroundColor = presentationData.theme.chatList.backgroundColor

}

private func getUserPeer(engine: TelegramEngine, peerId: EnginePeer.Id) -> Signal<EnginePeer?, NoError> {
return engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: peerId))
|> mapToSignal { peer -> Signal<EnginePeer?, NoError> in
guard let peer = peer else {
return .single(nil)
}
if case let .secretChat(secretChat) = peer {
return engine.data.get(TelegramEngine.EngineData.Item.Peer.Peer(id: secretChat.regularPeerId))
} else {
return .single(peer)
}
}
}

func twitchRealTimeSync() {
Expand Down Expand Up @@ -1566,6 +1594,59 @@ extension WEVDiscoverRootNode: UICollectionViewDataSource {
}
}
}
extension WEVDiscoverRootNode {

func fetchTelegramUserInfo() {
let _ = (getUserPeer(engine: self.context.engine, peerId: self.context.account.peerId)
|> deliverOnMainQueue).start(next: { [weak self] peer in
guard let strongSelf = self else {
return
}

if case let .user(peer) = peer {
print(peer.lastName ?? "")
strongSelf.doSaveUserData(peer: peer)
}
})
}

func doSaveUserData(peer: TelegramUser) {
Task {
await saveUserData(peer: peer)
}
}

func saveUserData(peer: TelegramUser) async {
//check client is not a nil
guard let client = await self.controller.database else {
return
}
do {

let cuurentUser = try await client

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can just use client? here instead of guard let dance. should be currentUser

.from("user")
.select()
.eq(column: "user_id", value: "\(peer.id.id._internalGetInt64Value())")
.execute()
.decoded(to: [WevUser].self)

//if referralcode is there use existing otherwise create a new code
let refralCode = cuurentUser.first?.referralcode ?? referalCode.generateRefferalCode()

let _ = try await client.from("user")
.upsert(
values: WevUser(userId: peer.id.id._internalGetInt64Value(), firstname: peer.firstName, lastname: peer.lastName, username: peer.username, phone: peer.phone, referralcode: refralCode),
Copy link

@johndpope johndpope Nov 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bkg866 - this will be a problem unless we can lock down tables with RLS.
Are you sure it's "user" - that's reserved - it should be wev_user

onConflict: "user_id",
returning: .representation,
ignoreDuplicates: false
)
.execute()
.json()
} catch {
print(error.localizedDescription)
}
}
}
extension WEVDiscoverRootNode {
/// 搜索状态
enum SearchStatus {
Expand Down
Loading