CCMain.m 222 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237
  1. //
  2. // CCMain.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "JDStatusBarNotification.h"
  35. #import "NCAutoUpload.h"
  36. #import "NCClientEncryption.h"
  37. #import "NCBridgeSwift.h"
  38. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  39. {
  40. tableMetadata *_metadata;
  41. BOOL _isRoot;
  42. BOOL _isViewDidLoad;
  43. BOOL _isSelectedMode;
  44. NSMutableDictionary *_selectedFileIDsMetadatas;
  45. NSUInteger _numSelectedFileIDsMetadatas;
  46. NSMutableArray *_queueSelector;
  47. NSMutableDictionary *_statusSwipeCell;
  48. UIImageView *_ImageTitleHomeCryptoCloud;
  49. UIView *_reMenuBackgroundView;
  50. UITapGestureRecognizer *_singleFingerTap;
  51. NSString *_directoryGroupBy;
  52. NSString *_directoryOrder;
  53. NSUInteger _failedAttempts;
  54. NSDate *_lockUntilDate;
  55. NSString *_fatherPermission;
  56. UIRefreshControl *_refreshControl;
  57. UIDocumentInteractionController *_docController;
  58. CCHud *_hud;
  59. CCHud *_hudDeterminate;
  60. // Datasource
  61. CCSectionDataSourceMetadata *_sectionDataSource;
  62. NSDate *_dateReadDataSource;
  63. // Search
  64. BOOL _isSearchMode;
  65. NSString *_searchFileName;
  66. NSMutableArray *_searchResultMetadatas;
  67. NSString *_noFilesSearchTitle;
  68. NSString *_noFilesSearchDescription;
  69. NSTimer *_timerWaitInput;
  70. // Login
  71. CCLoginWeb *_loginWeb;
  72. CCLogin *_loginVC;
  73. BOOL _loadingFolder;
  74. }
  75. @end
  76. @implementation CCMain
  77. #pragma --------------------------------------------------------------------------------------------
  78. #pragma mark ===== Init =====
  79. #pragma --------------------------------------------------------------------------------------------
  80. - (id)initWithCoder:(NSCoder *)aDecoder
  81. {
  82. if (self = [super initWithCoder:aDecoder]) {
  83. _directoryOrder = [CCUtility getOrderSettings];
  84. _directoryGroupBy = [CCUtility getGroupBySettings];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  90. }
  91. return self;
  92. }
  93. #pragma --------------------------------------------------------------------------------------------
  94. #pragma mark ===== View =====
  95. #pragma --------------------------------------------------------------------------------------------
  96. - (void)viewDidLoad
  97. {
  98. [super viewDidLoad];
  99. // init object
  100. _metadata = [tableMetadata new];
  101. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  102. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  104. _statusSwipeCell = [NSMutableDictionary new];
  105. _queueSelector = [NSMutableArray new];
  106. _isViewDidLoad = YES;
  107. _fatherPermission = @"";
  108. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  109. _searchResultMetadatas = [NSMutableArray new];
  110. _searchFileName = @"";
  111. _noFilesSearchTitle = @"";
  112. _noFilesSearchDescription = @"";
  113. // delegate
  114. self.tableView.delegate = self;
  115. self.tableView.tableFooterView = [UIView new];
  116. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  117. self.tableView.emptyDataSetDelegate = self;
  118. self.tableView.emptyDataSetSource = self;
  119. self.searchController.delegate = self;
  120. self.searchController.searchBar.delegate = self;
  121. [CCNetworking sharedNetworking].delegate = self;
  122. // Custom Cell
  123. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  125. // long press recognizer TableView
  126. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  127. [self.tableView addGestureRecognizer:longPressRecognizer];
  128. // Pull-to-Refresh
  129. [self createRefreshControl];
  130. // Register for 3D Touch Previewing if available
  131. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  132. {
  133. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  134. }
  135. // Back Button
  136. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  137. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  138. // reMenu Background
  139. _reMenuBackgroundView = [[UIView alloc] init];
  140. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  141. // if this is not Main (the Main uses inizializeMain)
  142. if (_isRoot == NO && app.activeAccount.length > 0) {
  143. // Settings this folder & delegate & Loading datasource
  144. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  145. // Load Datasource
  146. [self reloadDatasource:_serverUrl];
  147. // Read (File) Folder
  148. [self readFileReloadFolder];
  149. }
  150. // Title
  151. [self setTitle];
  152. // Search
  153. self.definesPresentationContext = YES;
  154. self.searchController.searchResultsUpdater = self;
  155. self.searchController.dimsBackgroundDuringPresentation = NO;
  156. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  157. [self.searchController.searchBar sizeToFit];
  158. self.searchController.searchBar.delegate = self;
  159. if (@available(iOS 11, *)) {
  160. self.navigationItem.searchController = self.searchController;
  161. self.navigationItem.hidesSearchBarWhenScrolling = true;
  162. self.navigationItem.searchController.searchBar.tintColor = [UIColor whiteColor];
  163. UITextField *textField = [self.searchController.searchBar valueForKey:@"searchField"];
  164. textField.textColor = [UIColor blackColor];
  165. textField.tintColor = [UIColor blackColor];
  166. UIView *backgroundView = textField.subviews.firstObject;
  167. backgroundView.backgroundColor = UIColor.whiteColor;
  168. backgroundView.layer.cornerRadius = 10;
  169. backgroundView.clipsToBounds = YES;
  170. } else {
  171. self.tableView.tableHeaderView = self.searchController.searchBar;
  172. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  173. }
  174. }
  175. // Apparirà
  176. - (void)viewWillAppear:(BOOL)animated
  177. {
  178. [super viewWillAppear:animated];
  179. // test
  180. if (app.activeAccount.length == 0)
  181. return;
  182. // Settings this folder & delegate & Loading datasource
  183. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  184. [CCNetworking sharedNetworking].delegate = self;
  185. // Color
  186. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  187. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  188. if (_isSelectedMode)
  189. [self setUINavigationBarSelected];
  190. else
  191. [self setUINavigationBarDefault];
  192. // If not editing mode remove _selectedFileIDs
  193. if (!self.tableView.editing)
  194. [_selectedFileIDsMetadatas removeAllObjects];
  195. // Plus Button
  196. [app plusButtonVisibile:true];
  197. }
  198. // E' arrivato
  199. - (void)viewDidAppear:(BOOL)animated
  200. {
  201. [super viewDidAppear:animated];
  202. // Active Main
  203. app.activeMain = self;
  204. // Test viewDidLoad
  205. if (_isViewDidLoad) {
  206. _isViewDidLoad = NO;
  207. } else {
  208. if (app.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  209. // Load Datasource
  210. [self reloadDatasource:_serverUrl];
  211. // Read (file) Folder
  212. [self readFileReloadFolder];
  213. }
  214. }
  215. // Title
  216. [self setTitle];
  217. }
  218. - (void)viewWillDisappear:(BOOL)animated
  219. {
  220. [super viewWillDisappear:animated];
  221. [self closeAllMenu];
  222. }
  223. - (void)didReceiveMemoryWarning
  224. {
  225. [super didReceiveMemoryWarning];
  226. // Dispose of any resources that can be recreated.
  227. }
  228. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  229. {
  230. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  231. [self closeAllMenu];
  232. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  233. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  234. // Portrait
  235. } else {
  236. // Landscape
  237. }
  238. [self.tableView reloadData];
  239. }];
  240. }
  241. - (BOOL)prefersStatusBarHidden
  242. {
  243. return NO;
  244. }
  245. // detect scroll for remove keyboard in search mode
  246. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  247. {
  248. if (_isSearchMode && scrollView == self.tableView) {
  249. [self.searchController.searchBar endEditing:YES];
  250. }
  251. }
  252. - (void)changeTheming
  253. {
  254. if (self.isViewLoaded && self.view.window)
  255. [app changeTheming:self];
  256. // Refresh control
  257. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  258. // Reload Table View
  259. [self tableViewReloadData];
  260. }
  261. #pragma --------------------------------------------------------------------------------------------
  262. #pragma mark ===== Initizlize Mail =====
  263. #pragma --------------------------------------------------------------------------------------------
  264. - (void)initializeMain:(NSNotification *)notification
  265. {
  266. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  267. _directoryGroupBy = nil;
  268. _directoryOrder = nil;
  269. _dateReadDataSource = nil;
  270. // test
  271. if (app.activeAccount.length == 0)
  272. return;
  273. if ([app.listMainVC count] == 0 || _isRoot) {
  274. // This is Root home main add list
  275. appDelegate.homeMain = self;
  276. _isRoot = YES;
  277. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  278. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  279. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  280. // go Home
  281. [self.navigationController popToRootViewControllerAnimated:NO];
  282. // setting Networking
  283. [CCNetworking sharedNetworking].delegate = self;
  284. [[CCNetworking sharedNetworking] settingAccount];
  285. // Remove search mode
  286. [self cancelSearchBar];
  287. // populate shared Link & User
  288. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  289. if (results) {
  290. appDelegate.sharesLink = results[0];
  291. appDelegate.sharesUserAndGroup = results[1];
  292. }
  293. // Load Datasource
  294. [self reloadDatasource:_serverUrl];
  295. // Read (File) Folder
  296. [self readFileReloadFolder];
  297. // Setting Theming
  298. [app settingThemingColorBrand];
  299. // Load photo datasorce
  300. if (appDelegate.activePhotos)
  301. [appDelegate.activePhotos reloadDatasourceForced];
  302. // remove all of detail
  303. if (appDelegate.activeDetail)
  304. [appDelegate.activeDetail removeAllView];
  305. // remove all Notification Messages
  306. [appDelegate.listOfNotifications removeAllObjects];
  307. // Not Photos Video in library ? then align
  308. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", app.activeAccount]];
  309. if ([recordsPhotoLibrary count] == 0) {
  310. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  311. }
  312. // Initializations
  313. [appDelegate applicationInitialized];
  314. } else {
  315. // reload datasource
  316. [self reloadDatasource:_serverUrl];
  317. }
  318. }
  319. #pragma --------------------------------------------------------------------------------------------
  320. #pragma mark ==== DZNEmptyDataSetSource ====
  321. #pragma --------------------------------------------------------------------------------------------
  322. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  323. {
  324. if (_loadingFolder)
  325. return NO;
  326. else
  327. return YES;
  328. }
  329. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  330. {
  331. return [UIColor whiteColor];
  332. }
  333. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  334. {
  335. if (_isSearchMode)
  336. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brand];
  337. else
  338. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  339. }
  340. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  341. {
  342. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  343. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  344. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  345. activityView.color = [NCBrandColor sharedInstance].brand;
  346. [activityView startAnimating];
  347. return activityView;
  348. }
  349. return nil;
  350. }
  351. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  352. {
  353. NSString *text;
  354. if (_isSearchMode) {
  355. text = _noFilesSearchTitle;
  356. } else {
  357. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  358. }
  359. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  360. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  361. }
  362. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  363. {
  364. NSString *text;
  365. if (_isSearchMode) {
  366. text = _noFilesSearchDescription;
  367. } else {
  368. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  369. }
  370. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  371. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  372. paragraph.alignment = NSTextAlignmentCenter;
  373. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  374. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  375. }
  376. #pragma --------------------------------------------------------------------------------------------
  377. #pragma mark ===== Text Field =====
  378. #pragma --------------------------------------------------------------------------------------------
  379. - (void)minCharTextFieldDidChange:(UITextField *)sender
  380. {
  381. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  382. if (alertController)
  383. {
  384. UITextField *fileName = alertController.textFields.firstObject;
  385. UIAlertAction *okAction = alertController.actions.lastObject;
  386. okAction.enabled = fileName.text.length > 0;
  387. }
  388. }
  389. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  390. [textField selectAll:textField];
  391. }
  392. #pragma --------------------------------------------------------------------------------------------
  393. #pragma mark ===== Graphic Window =====
  394. #pragma --------------------------------------------------------------------------------------------
  395. - (void)createRefreshControl
  396. {
  397. _refreshControl = [UIRefreshControl new];
  398. if (@available(iOS 11.0, *)) {
  399. [self.tableView setRefreshControl:_refreshControl];
  400. _refreshControl.tintColor = [UIColor whiteColor];
  401. } else {
  402. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  403. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  404. [self setRefreshControl:_refreshControl];
  405. }
  406. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  407. }
  408. - (void)deleteRefreshControl
  409. {
  410. [_refreshControl endRefreshing];
  411. self.refreshControl = nil;
  412. }
  413. - (void)refreshControlTarget
  414. {
  415. [self readFolder:_serverUrl];
  416. // Actuate `Peek` feedback (weak boom)
  417. AudioServicesPlaySystemSound(1519);
  418. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  419. }
  420. - (void)setTitle
  421. {
  422. // Color text self.navigationItem.title
  423. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  424. if (_isSelectedMode) {
  425. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  426. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  427. self.navigationItem.titleView = nil;
  428. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  429. } else {
  430. // we are in home : LOGO BRAND
  431. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  432. self.navigationItem.title = nil;
  433. if ([app.reachability isReachable] == NO)
  434. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  435. else
  436. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  437. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  438. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo:)];
  439. [singleTap setNumberOfTapsRequired:1];
  440. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  441. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  442. } else {
  443. self.navigationItem.title = _titleMain;
  444. }
  445. }
  446. }
  447. /*
  448. - (UIStatusBarStyle)preferredStatusBarStyle
  449. {
  450. UIBarStyle barStyle = self.navigationController.navigationBar.barStyle;
  451. if (barStyle == UIStatusBarStyleLightContent)
  452. return UIStatusBarStyleDefault;
  453. else
  454. return UIStatusBarStyleLightContent;
  455. }
  456. */
  457. - (void)setUINavigationBarDefault
  458. {
  459. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  460. UIBarButtonItem *buttonMore, *buttonNotification;
  461. // =
  462. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  463. buttonMore.enabled = true;
  464. // <
  465. self.navigationController.navigationBar.hidden = NO;
  466. // Notification
  467. if ([app.listOfNotifications count] > 0) {
  468. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  469. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  470. buttonNotification.enabled = true;
  471. }
  472. if (buttonNotification)
  473. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  474. else
  475. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  476. self.navigationItem.leftBarButtonItem = nil;
  477. }
  478. - (void)setUINavigationBarSelected
  479. {
  480. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  481. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  482. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  483. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  484. self.navigationItem.leftBarButtonItem = leftButton;
  485. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  486. }
  487. - (void)cancelSelect
  488. {
  489. [self tableViewSelect:NO];
  490. [app.reSelectMenu close];
  491. }
  492. - (void)closeAllMenu
  493. {
  494. // close Menu
  495. [app.reSelectMenu close];
  496. [app.reMainMenu close];
  497. // Close Menu Logo
  498. [CCMenuAccount dismissMenu];
  499. }
  500. #pragma --------------------------------------------------------------------------------------------
  501. #pragma mark ===== Document Picker =====
  502. #pragma --------------------------------------------------------------------------------------------
  503. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  504. {
  505. NSLog(@"Cancelled");
  506. }
  507. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  508. {
  509. NSLog(@"Cancelled");
  510. }
  511. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  512. {
  513. documentPicker.delegate = self;
  514. [self presentViewController:documentPicker animated:YES completion:nil];
  515. }
  516. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  517. {
  518. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  519. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  520. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  521. __block NSError *error;
  522. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  523. NSString *fileName = [url lastPathComponent];
  524. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  525. NSData *data = [NSData dataWithContentsOfURL:newURL];
  526. if (data && error == nil) {
  527. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  528. // Upload File
  529. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:serverUrl session:k_upload_session taskStatus: k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  530. } else {
  531. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  532. }
  533. } else {
  534. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  535. }
  536. }];
  537. }
  538. }
  539. - (void)openImportDocumentPicker
  540. {
  541. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  542. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  543. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  544. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  545. documentProviderMenu.delegate = self;
  546. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  547. }
  548. #pragma --------------------------------------------------------------------------------------------
  549. #pragma mark ===== Assets Picker =====
  550. #pragma --------------------------------------------------------------------------------------------
  551. -(void)dismissFormUploadAssets
  552. {
  553. [self reloadDatasource];
  554. }
  555. - (void)openAssetsPickerController
  556. {
  557. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  558. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  559. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  560. //UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil]; // DEPRECATED iOS9
  561. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[CTAssetsPickerController class]]];
  562. [app aspectNavigationControllerBar:navBar online:YES hidden:NO];
  563. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  564. dispatch_async(dispatch_get_main_queue(), ^{
  565. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  566. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeBottom];
  567. // init picker
  568. CTAssetsPickerController *picker = [CTAssetsPickerController new];
  569. // set delegate
  570. picker.delegate = self;
  571. // to show selection order
  572. //picker.showsSelectionIndex = YES;
  573. // to present picker as a form sheet in iPad
  574. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  575. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  576. // present picker
  577. [self presentViewController:picker animated:YES completion:nil];
  578. });
  579. }];
  580. }
  581. - (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
  582. {
  583. if (picker.selectedAssets.count > k_pickerControllerMax) {
  584. [app messageNotification:@"_info_" description:@"_limited_dimension_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  585. return NO;
  586. }
  587. return YES;
  588. }
  589. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  590. {
  591. [picker dismissViewControllerAnimated:YES completion:^{
  592. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  593. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:assets cryptated:NO session:k_upload_session delegate:self];
  594. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  595. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  596. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  597. [self presentViewController:navigationController animated:YES completion:nil];
  598. }];
  599. }
  600. // New folder or new photo or video
  601. - (void)returnCreate:(NSInteger)type
  602. {
  603. switch (type) {
  604. case k_returnCreateFolderPlain: {
  605. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  606. NSString *message;
  607. UIAlertController *alertController;
  608. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  609. message = @"/";
  610. } else {
  611. message = [serverUrl lastPathComponent];
  612. }
  613. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  614. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  615. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  616. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  617. }];
  618. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  619. NSLog(@"Cancel action");
  620. }];
  621. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  622. UITextField *fileName = alertController.textFields.firstObject;
  623. [self createFolder:fileName.text serverUrl:serverUrl];
  624. }];
  625. okAction.enabled = NO;
  626. [alertController addAction:cancelAction];
  627. [alertController addAction:okAction];
  628. [self presentViewController:alertController animated:YES completion:nil];
  629. }
  630. break;
  631. case k_returnCreateFotoVideoPlain: {
  632. [self openAssetsPickerController];
  633. }
  634. break;
  635. case k_returnCreateFilePlain: {
  636. [self openImportDocumentPicker];
  637. }
  638. break;
  639. case k_returnCreateFotoVideoEncrypted: {
  640. [self openAssetsPickerController];
  641. }
  642. break;
  643. case k_returnCreateFileEncrypted: {
  644. [self openImportDocumentPicker];
  645. }
  646. break;
  647. case k_returnCreateFileText: {
  648. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  649. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  650. [self presentViewController:navigationController animated:YES completion:nil];
  651. }
  652. break;
  653. }
  654. }
  655. #pragma --------------------------------------------------------------------------------------------
  656. #pragma mark ===== Save selected File =====
  657. #pragma --------------------------------------------------------------------------------------------
  658. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  659. {
  660. if (error)
  661. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  662. else
  663. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  664. }
  665. - (void)saveSelectedFiles
  666. {
  667. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  668. return;
  669. NSLog(@"[LOG] Start download selected files ...");
  670. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  671. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  672. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  673. for (tableMetadata *metadata in metadatas) {
  674. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  675. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  676. if (serverUrl)
  677. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  678. }
  679. }
  680. [_hud hideHud];
  681. });
  682. [self tableViewSelect:NO];
  683. }
  684. #pragma --------------------------------------------------------------------------------------------
  685. #pragma mark === Delegate Login ===
  686. #pragma --------------------------------------------------------------------------------------------
  687. - (void)loginSuccess:(NSInteger)loginType
  688. {
  689. [self readFolder:_serverUrl];
  690. }
  691. - (void)loginDisappear
  692. {
  693. app.activeLogin = nil;
  694. }
  695. #pragma mark -
  696. #pragma --------------------------------------------------------------------------------------------
  697. #pragma mark ===== Peek & Pop =====
  698. #pragma --------------------------------------------------------------------------------------------
  699. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  700. {
  701. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  702. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  703. if (metadata.thumbnailExists) {
  704. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  705. if (cell) {
  706. previewingContext.sourceRect = cell.frame;
  707. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  708. vc.delegate = self;
  709. vc.metadata = metadata;
  710. return vc;
  711. }
  712. }
  713. return nil;
  714. }
  715. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  716. {
  717. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  718. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  719. }
  720. #pragma mark -
  721. #pragma --------------------------------------------------------------------------------------------
  722. #pragma mark ==== External Sites ====
  723. #pragma --------------------------------------------------------------------------------------------
  724. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  725. {
  726. [[NCManageDatabase sharedInstance] deleteExternalSites];
  727. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  728. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  729. }
  730. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  731. {
  732. NSString *error = [NSString stringWithFormat:@"Get external site failure error %lu, %@", (long)errorCode, message];
  733. NSLog(@"[LOG] %@", error);
  734. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get External Sites Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  735. }
  736. #pragma --------------------------------------------------------------------------------------------
  737. #pragma mark ==== Activity ====
  738. #pragma --------------------------------------------------------------------------------------------
  739. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  740. {
  741. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  742. // Reload Activity Data Source
  743. [app.activeActivity reloadDatasource];
  744. }
  745. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  746. {
  747. NSString *error = [NSString stringWithFormat:@"Get Activity Server failure error %lu, %@", (long)errorCode, message];
  748. NSLog(@"[LOG] %@", error);
  749. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Activity Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  750. }
  751. #pragma --------------------------------------------------------------------------------------------
  752. #pragma mark ==== Notification ====
  753. #pragma --------------------------------------------------------------------------------------------
  754. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  755. {
  756. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  757. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  758. // Order by date
  759. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  760. OCNotifications *notification1 = obj1, *notification2 = obj2;
  761. return [notification2.date compare: notification1.date];
  762. }];
  763. // verify if listOfNotifications is changed
  764. NSString *old = @"", *new = @"";
  765. for (OCNotifications *notification in listOfNotifications)
  766. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  767. for (OCNotifications *notification in appDelegate.listOfNotifications)
  768. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  769. if (![new isEqualToString:old]) {
  770. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  771. // reload Notification view
  772. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  773. }
  774. // Update NavigationBar
  775. if (!_isSelectedMode) {
  776. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  777. }
  778. });
  779. }
  780. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  781. {
  782. NSString *error = [NSString stringWithFormat:@"Get Notification Server failure error %lu, %@", (long)errorCode, message];
  783. NSLog(@"[LOG] %@", error);
  784. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Notification Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  785. // Update NavigationBar
  786. if (!_isSelectedMode)
  787. [self setUINavigationBarDefault];
  788. }
  789. - (void)viewNotification
  790. {
  791. if ([app.listOfNotifications count] > 0) {
  792. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  793. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  794. [self presentViewController:notificationVC animated:YES completion:nil];
  795. }
  796. }
  797. #pragma --------------------------------------------------------------------------------------------
  798. #pragma mark ==== User Profile ====
  799. #pragma --------------------------------------------------------------------------------------------
  800. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  801. {
  802. NSString *error = [NSString stringWithFormat:@"Get user profile failure error %lu, %@", (long)errorCode, message];
  803. NSLog(@"[LOG] %@", error);
  804. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get user profile Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  805. }
  806. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  807. {
  808. // Update User (+ userProfile.id)
  809. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  810. // Get Account Active
  811. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  812. // Setting App active account
  813. [app settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  814. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  815. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  816. //UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  817. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  818. if (avatar)
  819. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  820. else
  821. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  822. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  823. });
  824. }
  825. #pragma --------------------------------------------------------------------------------------------
  826. #pragma mark ==== Capabilities ====
  827. #pragma --------------------------------------------------------------------------------------------
  828. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  829. {
  830. // Unauthorized
  831. if (errorCode == kOCErrorServerUnauthorized)
  832. [app openLoginView:self loginType:loginModifyPasswordUser];
  833. NSString *error = [NSString stringWithFormat:@"Get Capabilities failure error %lu, %@", (long)errorCode, message];
  834. NSLog(@"[LOG] %@", error);
  835. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Capabilities of Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  836. // Change Theming color
  837. [app settingThemingColorBrand];
  838. }
  839. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  840. {
  841. // Update capabilities db
  842. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  843. // ------ THEMING -----------------------------------------------------------------------
  844. // Download Theming Background & Change Theming color
  845. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  846. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  847. //UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  848. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  849. if (themingBackground)
  850. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  851. else
  852. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  853. }
  854. dispatch_async(dispatch_get_main_queue(), ^{
  855. [app settingThemingColorBrand];
  856. });
  857. });
  858. // ------ SEARCH ------------------------------------------------------------------------
  859. // Search bar if change version
  860. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  861. [self cancelSearchBar];
  862. }
  863. // ------ GET SERVICE SERVER ------------------------------------------------------------
  864. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  865. // Read External Sites
  866. if (capabilities.isExternalSitesServerEnabled) {
  867. metadataNet.action = actionGetExternalSitesServer;
  868. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  869. }
  870. // Read Share
  871. if (capabilities.isFilesSharingAPIEnabled) {
  872. [app.sharesID removeAllObjects];
  873. metadataNet.action = actionReadShareServer;
  874. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  875. }
  876. // Read Notification
  877. metadataNet.action = actionGetNotificationServer;
  878. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  879. // Read User Profile
  880. metadataNet.action = actionGetUserProfile;
  881. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  882. // Read Activity
  883. metadataNet.action = actionGetActivityServer;
  884. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  885. }
  886. #pragma mark -
  887. #pragma --------------------------------------------------------------------------------------------
  888. #pragma mark ==== Request Server Information ====
  889. #pragma --------------------------------------------------------------------------------------------
  890. - (void)requestServerCapabilities
  891. {
  892. // test
  893. if (app.activeAccount.length == 0)
  894. return;
  895. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  896. metadataNet.action = actionGetCapabilities;
  897. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  898. }
  899. #pragma mark -
  900. #pragma --------------------------------------------------------------------------------------------
  901. #pragma mark ==== Middleware Ping ====
  902. #pragma --------------------------------------------------------------------------------------------
  903. - (void)middlewarePing
  904. {
  905. // test
  906. if (app.activeAccount.length == 0)
  907. return;
  908. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  909. metadataNet.action = actionMiddlewarePing;
  910. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  911. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  912. }
  913. #pragma mark -
  914. #pragma --------------------------------------------------------------------------------------------
  915. #pragma mark ==== Download Thumbnail Delegate ====
  916. #pragma --------------------------------------------------------------------------------------------
  917. - (void)downloadThumbnailFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  918. {
  919. NSLog(@"[LOG] Download Thumbnail Failure error %lu, %@", (long)errorCode, message);
  920. }
  921. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  922. {
  923. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  924. if ([self indexPathIsValid:indexPath]) {
  925. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  926. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  927. }
  928. }
  929. #pragma --------------------------------------------------------------------------------------------
  930. #pragma mark ==== Download ====
  931. #pragma --------------------------------------------------------------------------------------------
  932. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  933. {
  934. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  935. // File do not exists on server, remove in local
  936. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  937. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  938. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  939. if (metadata.directory && serverUrl) {
  940. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  941. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  942. }
  943. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  944. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  945. }
  946. if ([selector isEqualToString:selectorLoadViewImage]) {
  947. dispatch_async(dispatch_get_main_queue(), ^{
  948. // Updating Detail
  949. if (app.activeDetail)
  950. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  951. // Updating Photos
  952. if (app.activePhotos)
  953. [app.activePhotos downloadFileFailure:errorCode];
  954. });
  955. } else {
  956. if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized)
  957. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  958. }
  959. [self reloadDatasource:serverUrl];
  960. }
  961. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  962. {
  963. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  964. if (metadata == nil)
  965. return;
  966. // Download
  967. if ([selector isEqualToString:selectorDownloadFile]) {
  968. [self reloadDatasource:serverUrl];
  969. }
  970. // Synchronized
  971. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  972. [self reloadDatasource:serverUrl];
  973. }
  974. // add Favorite
  975. if ([selector isEqualToString:selectorAddFavorite]) {
  976. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  977. }
  978. // open View File
  979. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  980. [self reloadDatasource:serverUrl];
  981. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  982. selector = selectorOpenIn;
  983. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  984. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  985. selector = selectorOpenIn;
  986. } else {
  987. _metadata = metadata;
  988. if ([self shouldPerformSegue])
  989. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  990. }
  991. }
  992. // Open with...
  993. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  994. [self reloadDatasource:serverUrl];
  995. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  996. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  997. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName]];
  998. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  999. _docController.delegate = self;
  1000. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1001. }
  1002. // Save to Photo Album
  1003. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1004. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1005. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1006. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1007. if (image)
  1008. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1009. else
  1010. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1011. }
  1012. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1013. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1014. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName])) {
  1015. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1016. } else {
  1017. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1018. }
  1019. }
  1020. [self reloadDatasource:serverUrl];
  1021. }
  1022. // Copy File
  1023. if ([selector isEqualToString:selectorLoadCopy]) {
  1024. [self reloadDatasource:serverUrl];
  1025. [self copyFileToPasteboard:metadata];
  1026. }
  1027. //download file plist
  1028. if ([selector isEqualToString:selectorLoadPlist]) {
  1029. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1030. long countSelectorLoadPlist = 0;
  1031. for (NSOperation *operation in [app.netQueue operations]) {
  1032. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1033. countSelectorLoadPlist++;
  1034. }
  1035. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1036. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:directoryID] && directoryID) {
  1037. dispatch_async(dispatch_get_main_queue(), ^{
  1038. [self reloadDatasource:serverUrl];
  1039. });
  1040. }
  1041. });
  1042. }
  1043. //selectorLoadViewImage
  1044. if ([selector isEqualToString:selectorLoadViewImage]) {
  1045. // Detail
  1046. if (app.activeDetail)
  1047. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1048. // Photos
  1049. if (app.activePhotos)
  1050. [app.activePhotos downloadFileSuccess:metadata];
  1051. [self reloadDatasource:serverUrl];
  1052. }
  1053. // if exists postselector call self with selectorPost
  1054. if ([selectorPost length] > 0)
  1055. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1056. // Auto Download Upload
  1057. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1058. // ONLY BACKGROUND
  1059. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1060. } else {
  1061. // ONLY FOREFROUND
  1062. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1063. }
  1064. }
  1065. - (void)downloadSelectedFilesFolders
  1066. {
  1067. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1068. return;
  1069. NSLog(@"[LOG] Start download selected ...");
  1070. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1071. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1072. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1073. for (tableMetadata *metadata in selectedMetadatas) {
  1074. if (metadata.directory) {
  1075. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1076. if (serverUrl) {
  1077. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1078. [[CCSynchronize sharedSynchronize] readFolder:serverUrl selector:selectorReadFolderWithDownload];
  1079. }
  1080. } else {
  1081. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFileWithDownload];
  1082. }
  1083. }
  1084. [_hud hideHud];
  1085. });
  1086. [self tableViewSelect:NO];
  1087. }
  1088. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1089. {
  1090. }
  1091. #pragma --------------------------------------------------------------------------------------------
  1092. #pragma mark ===== Upload new Photos/Videos =====
  1093. #pragma --------------------------------------------------------------------------------------------
  1094. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1095. {
  1096. // Auto Download Upload
  1097. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll] || [selector isEqualToString:selectorUploadFile]) {
  1098. if ([[NCManageDatabase sharedInstance] getPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier] > k_priorityAutoUploadStop) {
  1099. // Change priority Auto Upload
  1100. if ([[NCManageDatabase sharedInstance] setPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier priority:k_priorityAutoUploadError]) {
  1101. // Activity
  1102. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:message type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1103. }
  1104. if (errorCode != kCFURLErrorCancelled)
  1105. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1106. } else {
  1107. // Delete record on Table Auto Upload
  1108. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier selector:selector];
  1109. // Activity
  1110. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:@"Too many error, file deleted" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1111. [app messageNotification:@"_upload_file_" description:@"Too many error, file deleted, see Activity for more info" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1112. }
  1113. } else {
  1114. // Read File test do not exists
  1115. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1116. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1117. // reUpload
  1118. if (metadata)
  1119. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1120. }
  1121. // Print error
  1122. else if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized) {
  1123. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1124. }
  1125. }
  1126. [self reloadDatasource:serverUrl];
  1127. }
  1128. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1129. {
  1130. // Auto Download Upload
  1131. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1132. // ONLY BACKGROUND
  1133. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1134. } else {
  1135. // ONLY FOREFROUND
  1136. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1137. }
  1138. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1139. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1140. [self readFolder:serverUrl];
  1141. } else {
  1142. [self reloadDatasource:serverUrl];
  1143. }
  1144. });
  1145. }
  1146. //
  1147. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1148. //
  1149. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1150. {
  1151. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1152. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1153. });
  1154. }
  1155. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1156. {
  1157. NSArray *assets = [arguments objectAtIndex:0];
  1158. NSString *serverUrl = [arguments objectAtIndex:1];
  1159. BOOL useSubFolder = [[arguments objectAtIndex:2] boolValue];
  1160. NSString *session = [arguments objectAtIndex:3];
  1161. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1162. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1163. if (!directoryID) return;
  1164. // if request create the folder for Photos & the subfolders
  1165. if ([autoUploadPath isEqualToString:serverUrl])
  1166. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1167. return;
  1168. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1169. for (PHAsset *asset in assets) {
  1170. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType];
  1171. NSDate *assetDate = asset.creationDate;
  1172. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1173. // Create serverUrl if use sub folder
  1174. if (useSubFolder) {
  1175. [formatter setDateFormat:@"yyyy"];
  1176. NSString *yearString = [formatter stringFromDate:assetDate];
  1177. [formatter setDateFormat:@"MM"];
  1178. NSString *monthString = [formatter stringFromDate:assetDate];
  1179. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1180. }
  1181. // Check if is in upload
  1182. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1183. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1184. if ([isRecordInSessions count] > 0) {
  1185. // next upload
  1186. continue;
  1187. } else {
  1188. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1189. metadataNet.action = actionReadFile;
  1190. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1191. metadataNet.fileName = fileName;
  1192. metadataNet.session = session;
  1193. metadataNet.selector = selectorReadFileUploadFile;
  1194. metadataNet.serverUrl = serverUrl;
  1195. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1196. }
  1197. }
  1198. }
  1199. #pragma --------------------------------------------------------------------------------------------
  1200. #pragma mark ==== Read File ====
  1201. #pragma --------------------------------------------------------------------------------------------
  1202. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1203. {
  1204. // Unauthorized
  1205. if (errorCode == kOCErrorServerUnauthorized)
  1206. [app openLoginView:self loginType:loginModifyPasswordUser];
  1207. // UploadFile
  1208. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1209. // File not exists
  1210. if (errorCode == 404) {
  1211. metadataNet.errorCode = 0;
  1212. metadataNet.selector = selectorUploadFile;
  1213. metadataNet.selectorPost = nil;
  1214. metadataNet.taskStatus = k_taskStatusResume;
  1215. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1216. } else {
  1217. // error ho many retry befor notification and go to on next asses
  1218. if (metadataNet.errorRetry < 3) {
  1219. // Retry read file
  1220. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1221. } else {
  1222. // STOP check file, view message error
  1223. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1224. }
  1225. }
  1226. }
  1227. }
  1228. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1229. {
  1230. // Read Folder
  1231. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1232. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1233. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1234. [self readFolder:metadataNet.serverUrl];
  1235. }
  1236. }
  1237. // UploadFile
  1238. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1239. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1240. metadataNet.selector = selectorUploadFile;
  1241. metadataNet.selectorPost = nil;
  1242. metadataNet.taskStatus = k_taskStatusResume;
  1243. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1244. }
  1245. }
  1246. - (void)readFileReloadFolder
  1247. {
  1248. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1249. return;
  1250. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1251. metadataNet.action = actionReadFile;
  1252. metadataNet.priority = NSOperationQueuePriorityHigh;
  1253. metadataNet.selector = selectorReadFileReloadFolder;
  1254. metadataNet.serverUrl = _serverUrl;
  1255. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1256. }
  1257. #pragma --------------------------------------------------------------------------------------------
  1258. #pragma mark ==== Read Folder ====
  1259. #pragma --------------------------------------------------------------------------------------------
  1260. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1261. {
  1262. // stoprefresh
  1263. [_refreshControl endRefreshing];
  1264. // Unauthorized
  1265. if (errorCode == kOCErrorServerUnauthorized)
  1266. [app openLoginView:self loginType:loginModifyPasswordUser];
  1267. _loadingFolder = NO;
  1268. [self tableViewReloadData];
  1269. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1270. // verify active user
  1271. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1272. if (message && [record.account isEqualToString:metadataNet.account])
  1273. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1274. [self reloadDatasource:metadataNet.serverUrl];
  1275. }
  1276. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1277. {
  1278. // stoprefresh
  1279. [_refreshControl endRefreshing];
  1280. // verify active user
  1281. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1282. if (![record.account isEqualToString:metadataNet.account])
  1283. return;
  1284. // save father e update permission
  1285. if(!_isSearchMode && metadataFolder)
  1286. _fatherPermission = metadataFolder.permissions;
  1287. NSArray *recordsInSessions;
  1288. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1289. if (_isSearchMode) {
  1290. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1291. } else {
  1292. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag];
  1293. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1294. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1295. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1296. }
  1297. for (tableMetadata *metadata in metadatas) {
  1298. // verify if the record is in download/upload progress
  1299. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1300. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1301. // is in Download or Upload
  1302. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1303. continue;
  1304. }
  1305. }
  1306. // Insert in Array
  1307. [metadatasToInsertInDB addObject:metadata];
  1308. }
  1309. // insert in Database
  1310. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl];
  1311. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1312. // read plist
  1313. if (!_isSearchMode)
  1314. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1315. // File is changed ??
  1316. if (!_isSearchMode && metadatasToInsertInDB)
  1317. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1318. });
  1319. // Search Mode
  1320. if (_isSearchMode) {
  1321. // Fix managed -> Unmanaged _searchResultMetadatas
  1322. if (metadatasToInsertInDB)
  1323. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1324. [self reloadDatasource:metadataNet.serverUrl];
  1325. }
  1326. // this is the same directory
  1327. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1328. // reload
  1329. [self reloadDatasource:metadataNet.serverUrl];
  1330. // Enable change user
  1331. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1332. _loadingFolder = NO;
  1333. [self tableViewReloadData];
  1334. }
  1335. }
  1336. - (void)readFolder:(NSString *)serverUrl
  1337. {
  1338. // init control
  1339. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1340. [_refreshControl endRefreshing];
  1341. return;
  1342. }
  1343. // Search Mode
  1344. if (_isSearchMode) {
  1345. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1346. _searchFileName = @""; // forced reload searchg
  1347. [self updateSearchResultsForSearchController:self.searchController];
  1348. return;
  1349. }
  1350. _loadingFolder = YES;
  1351. [self tableViewReloadData];
  1352. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  1353. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1354. metadataNet.action = actionReadFolder;
  1355. metadataNet.date = [NSDate date];
  1356. metadataNet.depth = @"1";
  1357. metadataNet.directoryID = directory.directoryID;
  1358. metadataNet.priority = NSOperationQueuePriorityHigh;
  1359. metadataNet.selector = selectorReadFolder;
  1360. metadataNet.serverUrl = serverUrl;
  1361. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1362. }
  1363. #pragma mark -
  1364. #pragma --------------------------------------------------------------------------------------------
  1365. #pragma mark ===== Search =====
  1366. #pragma --------------------------------------------------------------------------------------------
  1367. -(void)searchStartTimer
  1368. {
  1369. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1370. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:@"infinity" date:nil selector:selectorSearch delegate:self];
  1371. _noFilesSearchTitle = @"";
  1372. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1373. [self.tableView reloadEmptyDataSet];
  1374. }
  1375. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1376. {
  1377. //[self setNeedsStatusBarAppearanceUpdate];
  1378. _isSearchMode = YES;
  1379. [self deleteRefreshControl];
  1380. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1381. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1382. _searchFileName = fileName;
  1383. // First : filter
  1384. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1385. if (!directoryID) return;
  1386. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileName CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1387. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1388. [_searchResultMetadatas removeAllObjects];
  1389. for (tableMetadata *record in records)
  1390. [_searchResultMetadatas addObject:record];
  1391. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1392. metadataNet.account = app.activeAccount;
  1393. metadataNet.directoryID = directoryID;
  1394. metadataNet.selector = selectorSearch;
  1395. metadataNet.serverUrl = _serverUrl;
  1396. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1397. // Version >= 12
  1398. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1399. [_timerWaitInput invalidate];
  1400. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1401. }
  1402. }
  1403. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1404. [self reloadDatasource];
  1405. }
  1406. }
  1407. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1408. {
  1409. [self cancelSearchBar];
  1410. [self readFolder:_serverUrl];
  1411. }
  1412. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1413. {
  1414. // Unauthorized
  1415. if (errorCode == kOCErrorServerUnauthorized)
  1416. [app openLoginView:self loginType:loginModifyPasswordUser];
  1417. if (message && errorCode != kOCErrorServerUnauthorized)
  1418. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1419. _searchFileName = @"";
  1420. }
  1421. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1422. {
  1423. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1424. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1425. }
  1426. - (void)cancelSearchBar
  1427. {
  1428. if (self.searchController.active) {
  1429. [self.searchController setActive:NO];
  1430. [self createRefreshControl];
  1431. _isSearchMode = NO;
  1432. _searchFileName = @"";
  1433. _dateReadDataSource = nil;
  1434. _searchResultMetadatas = [NSMutableArray new];
  1435. [self reloadDatasource];
  1436. }
  1437. //[self setNeedsStatusBarAppearanceUpdate];
  1438. }
  1439. #pragma mark -
  1440. #pragma --------------------------------------------------------------------------------------------
  1441. #pragma mark ===== Delete File or Folder =====
  1442. #pragma --------------------------------------------------------------------------------------------
  1443. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1444. {
  1445. // Unauthorized
  1446. if (errorCode == kOCErrorServerUnauthorized)
  1447. [app openLoginView:self loginType:loginModifyPasswordUser];
  1448. NSLog(@"[LOG] Delete File failure error %lu, %@", (long)errorCode, message);
  1449. [self deleteFileOrFolderSuccess:metadataNet];
  1450. }
  1451. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1452. {
  1453. [_queueSelector removeObject:metadataNet.selector];
  1454. if ([_queueSelector count] == 0) {
  1455. [_hud hideHud];
  1456. // next
  1457. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1458. if ([_selectedFileIDsMetadatas count] > 0) {
  1459. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1460. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1461. } else {
  1462. // End Select Table View
  1463. [self tableViewSelect:NO];
  1464. // Reload
  1465. if (_isSearchMode)
  1466. [self readFolder:metadataNet.serverUrl];
  1467. else
  1468. [self reloadDatasource:metadataNet.serverUrl];
  1469. }
  1470. }
  1471. }
  1472. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1473. {
  1474. [_queueSelector addObject:selectorDelete];
  1475. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1476. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1477. }
  1478. - (void)deleteFile
  1479. {
  1480. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1481. return;
  1482. [_queueSelector removeAllObjects];
  1483. if ([_selectedFileIDsMetadatas count] > 0) {
  1484. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1485. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1486. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1487. } else {
  1488. _numSelectedFileIDsMetadatas = 1;
  1489. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1490. }
  1491. }
  1492. #pragma --------------------------------------------------------------------------------------------
  1493. #pragma mark ===== Rename / Move =====
  1494. #pragma --------------------------------------------------------------------------------------------
  1495. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1496. {
  1497. [self readFolder:metadataNet.serverUrl];
  1498. }
  1499. - (void)renameFile:(NSArray *)arguments
  1500. {
  1501. tableMetadata* metadata = [arguments objectAtIndex:0];
  1502. NSString *fileName = [arguments objectAtIndex:1];
  1503. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1504. }
  1505. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1506. {
  1507. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1508. [_hud hideHud];
  1509. if (message && errorCode != kOCErrorServerUnauthorized)
  1510. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1511. // End Select Table View
  1512. [self tableViewSelect:NO];
  1513. // reload Datasource
  1514. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1515. [self readFolder:metadataNet.serverUrl];
  1516. else
  1517. [self reloadDatasource];
  1518. }
  1519. }
  1520. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1521. {
  1522. [_queueSelector removeObject:metadataNet.selector];
  1523. if ([_queueSelector count] == 0) {
  1524. [_hud hideHud];
  1525. NSString *fileName = metadataNet.fileName;
  1526. NSString *directoryID = metadataNet.directoryID;
  1527. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1528. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1529. if (!serverUrlTo) return;
  1530. // FILE -> Metadata
  1531. if (metadataNet.directory == NO)
  1532. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1533. // DIRECTORY -> Directory - CCMetadata
  1534. if (metadataNet.directory == YES) {
  1535. // delete all dir / subdir
  1536. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1537. // move metadata
  1538. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1539. // Add new directory
  1540. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1541. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1542. }
  1543. // next
  1544. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1545. if ([_selectedFileIDsMetadatas count] > 0) {
  1546. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1547. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1548. } else {
  1549. // End Select Table View
  1550. [self tableViewSelect:NO];
  1551. // reload Datasource
  1552. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1553. [self readFolder:metadataNet.serverUrl];
  1554. else
  1555. [self reloadDatasource];
  1556. }
  1557. }
  1558. }
  1559. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1560. {
  1561. tableMetadata *metadata = [arguments objectAtIndex:0];
  1562. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1563. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1564. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1565. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1566. if (!serverUrl) return;
  1567. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1568. if (!directoryIDTo) return;
  1569. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withUserID:app.activeUserID withPassword:app.activePassword withUrl:app.activeUrl];
  1570. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1571. if(!error) {
  1572. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1573. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1574. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1575. }];
  1576. [alert addAction:ok];
  1577. [self presentViewController:alert animated:YES completion:nil];
  1578. });
  1579. // End Select Table View
  1580. [self tableViewSelect:NO];
  1581. // reload Datasource
  1582. [self readFileReloadFolder];
  1583. return;
  1584. }
  1585. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1586. metadataNet.action = actionMoveFileOrFolder;
  1587. metadataNet.directory = metadata.directory;
  1588. metadataNet.fileID = metadata.fileID;
  1589. metadataNet.directoryID = metadata.directoryID;
  1590. metadataNet.directoryIDTo = directoryIDTo;
  1591. metadataNet.fileName = metadata.fileName;
  1592. metadataNet.fileNameTo = metadata.fileName;
  1593. metadataNet.etag = metadata.etag;
  1594. metadataNet.selector = selectorMove;
  1595. metadataNet.serverUrl = serverUrl;
  1596. metadataNet.serverUrlTo = serverUrlTo;
  1597. [_queueSelector addObject:metadataNet.selector];
  1598. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1599. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1600. }
  1601. // DELEGATE : Move
  1602. - (void)dismissMove
  1603. {
  1604. [self reloadDatasource];
  1605. }
  1606. // DELEGATE : Move
  1607. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1608. {
  1609. [_queueSelector removeAllObjects];
  1610. if ([_selectedFileIDsMetadatas count] > 0) {
  1611. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1612. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1613. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1614. } else {
  1615. _numSelectedFileIDsMetadatas = 1;
  1616. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1617. }
  1618. }
  1619. - (void)moveOpenWindow:(NSArray *)indexPaths
  1620. {
  1621. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1622. return;
  1623. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1624. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1625. viewController.delegate = self;
  1626. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1627. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1628. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1629. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1630. viewController.networkingOperationQueue = app.netQueue;
  1631. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1632. [self presentViewController:navigationController animated:YES completion:nil];
  1633. }
  1634. #pragma --------------------------------------------------------------------------------------------
  1635. #pragma mark ===== Create folder =====
  1636. #pragma --------------------------------------------------------------------------------------------
  1637. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1638. {
  1639. // Unauthorized
  1640. if (errorCode == kOCErrorServerUnauthorized)
  1641. [app openLoginView:self loginType:loginModifyPasswordUser];
  1642. if (message && errorCode != kOCErrorServerUnauthorized)
  1643. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1644. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1645. [self reloadDatasource];
  1646. // We are in directory fail ?
  1647. CCMain *vc = [app.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1648. if (vc)
  1649. [vc.navigationController popViewControllerAnimated:YES];
  1650. }
  1651. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1652. {
  1653. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1654. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1655. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1656. if (metadata) {
  1657. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1658. metadata.fileID = metadataNet.fileID;
  1659. metadata.date = metadataNet.date;
  1660. metadata.permissions = @"RDNVCK";
  1661. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1662. [self reloadDatasource];
  1663. } else {
  1664. [self readFileReloadFolder];
  1665. }
  1666. }
  1667. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1668. {
  1669. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1670. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1671. if (![fileNameFolder length]) return;
  1672. //if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1673. //else metadataNet.serverUrl = _serverUrl;
  1674. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1675. if (!directoryID) return;
  1676. metadataNet.action = actionCreateFolder;
  1677. metadataNet.directoryID = directoryID;
  1678. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1679. metadataNet.fileName = fileNameFolder;
  1680. metadataNet.selector = selectorCreateFolder;
  1681. metadataNet.serverUrl = serverUrl;
  1682. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1683. // Create Directory on metadata
  1684. tableMetadata *metadata = [CCUtility createMetadataWithAccount:app.activeAccount date:[NSDate date] directory:YES fileID:metadataNet.fileID directoryID:metadataNet.directoryID fileName:metadataNet.fileName etag:@"" size:0 status:k_metadataStatusNormal];
  1685. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1686. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1687. [self reloadDatasource];
  1688. }
  1689. #pragma --------------------------------------------------------------------------------------------
  1690. #pragma mark ===== Encrypted / Decrypted Folder =====
  1691. #pragma --------------------------------------------------------------------------------------------
  1692. - (void)encyptedDecryptedFolder
  1693. {
  1694. }
  1695. #pragma --------------------------------------------------------------------------------------------
  1696. #pragma mark ===== Encrypted/Decrypted File =====
  1697. #pragma --------------------------------------------------------------------------------------------
  1698. - (void)encryptedSelectedFiles
  1699. {
  1700. }
  1701. - (void)decryptedSelectedFiles
  1702. {
  1703. }
  1704. - (void)cmdEncryptedDecryptedFile
  1705. {
  1706. }
  1707. - (void)encryptedFile:(tableMetadata *)metadata
  1708. {
  1709. }
  1710. - (void)decryptedFile:(tableMetadata *)metadata
  1711. {
  1712. }
  1713. #pragma --------------------------------------------------------------------------------------------
  1714. #pragma mark ===== Progress & Task Button =====
  1715. #pragma --------------------------------------------------------------------------------------------
  1716. - (void)triggerProgressTask:(NSNotification *)notification
  1717. {
  1718. NSDictionary *dict = notification.userInfo;
  1719. NSString *fileID = [dict valueForKey:@"fileID"];
  1720. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1721. float progress = [[dict valueForKey:@"progress"] floatValue];
  1722. // Check
  1723. if (!fileID || [fileID isEqualToString: @""])
  1724. return;
  1725. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1726. if (![serverUrl isEqualToString:_serverUrl])
  1727. return;
  1728. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1729. if ([self indexPathIsValid:indexPath]) {
  1730. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1731. cell.progressView.progressTintColor = [UIColor blackColor];
  1732. cell.progressView.hidden = NO;
  1733. [cell.progressView setProgress:progress];
  1734. }
  1735. }
  1736. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1737. {
  1738. UITouch * touch = [[event allTouches] anyObject];
  1739. CGPoint location = [touch locationInView:self.tableView];
  1740. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1741. if ([self indexPathIsValid:indexPath]) {
  1742. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1743. if (metadata)
  1744. [self reloadTaskButton:metadata];
  1745. }
  1746. }
  1747. - (void)reloadTaskButton:(tableMetadata *)metadata
  1748. {
  1749. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1750. __block NSURLSessionTask *findTask;
  1751. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1752. NSString *fileID = metadata.fileID;
  1753. // DOWNLOAD
  1754. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1755. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1756. for (NSURLSessionUploadTask *task in downloadTasks)
  1757. if (task.taskIdentifier == sessionTaskIdentifier) {
  1758. findTask = task;
  1759. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1760. [task cancel];
  1761. }
  1762. if (!findTask) {
  1763. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1764. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1765. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1766. }
  1767. }];
  1768. }
  1769. // UPLOAD
  1770. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1771. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1772. for (NSURLSessionUploadTask *task in uploadTasks)
  1773. if (task.taskIdentifier == sessionTaskIdentifier) {
  1774. findTask = task;
  1775. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1776. [task cancel];
  1777. }
  1778. if (!findTask) {
  1779. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1780. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1781. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1782. }
  1783. }];
  1784. }
  1785. }
  1786. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1787. {
  1788. UITouch * touch = [[event allTouches] anyObject];
  1789. CGPoint location = [touch locationInView:self.tableView];
  1790. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1791. if ([self indexPathIsValid:indexPath]) {
  1792. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1793. if (metadata)
  1794. [self cancelTaskButton:metadata reloadTable:YES];
  1795. }
  1796. }
  1797. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1798. {
  1799. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1800. __block NSURLSessionTask *findTask;
  1801. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1802. NSString *fileID = metadata.fileID;
  1803. // DOWNLOAD
  1804. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1805. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1806. for (NSURLSessionTask *task in downloadTasks)
  1807. if (task.taskIdentifier == sessionTaskIdentifier) {
  1808. findTask = task;
  1809. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1810. [task cancel];
  1811. }
  1812. if (!findTask) {
  1813. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1814. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1815. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1816. }
  1817. }];
  1818. }
  1819. // UPLOAD
  1820. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1821. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1822. for (NSURLSessionUploadTask *task in uploadTasks)
  1823. if (task.taskIdentifier == sessionTaskIdentifier) {
  1824. findTask = task;
  1825. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1826. [task cancel];
  1827. }
  1828. if (!findTask) {
  1829. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1830. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1831. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1832. }
  1833. }];
  1834. }
  1835. }
  1836. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1837. {
  1838. UITouch * touch = [[event allTouches] anyObject];
  1839. CGPoint location = [touch locationInView:self.tableView];
  1840. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1841. if ([self indexPathIsValid:indexPath]) {
  1842. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1843. if (metadata)
  1844. [self stopTaskButton:metadata];
  1845. }
  1846. }
  1847. - (void)stopTaskButton:(tableMetadata *)metadata
  1848. {
  1849. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1850. __block NSURLSessionTask *findTask;
  1851. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1852. NSString *fileID = metadata.fileID;
  1853. // UPLOAD
  1854. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1855. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1856. for (NSURLSessionUploadTask *task in uploadTasks)
  1857. if (task.taskIdentifier == sessionTaskIdentifier) {
  1858. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1859. findTask = task;
  1860. [task cancel];
  1861. }
  1862. if (!findTask) {
  1863. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1864. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1865. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1866. }
  1867. }];
  1868. }
  1869. }
  1870. #pragma --------------------------------------------------------------------------------------------
  1871. #pragma mark ===== Shared =====
  1872. #pragma --------------------------------------------------------------------------------------------
  1873. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1874. {
  1875. [_hud hideHud];
  1876. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1877. // change account ?
  1878. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1879. if([record.account isEqualToString:metadataNet.account] == NO)
  1880. return;
  1881. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1882. if (result) {
  1883. appDelegate.sharesLink = result[0];
  1884. appDelegate.sharesUserAndGroup = result[1];
  1885. }
  1886. // Notify Shares View
  1887. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1888. if (openWindow) {
  1889. if (_shareOC) {
  1890. [_shareOC reloadData];
  1891. } else {
  1892. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  1893. // Apriamo la view
  1894. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1895. _shareOC.delegate = self;
  1896. _shareOC.metadata = metadata;
  1897. _shareOC.serverUrl = metadataNet.serverUrl;
  1898. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  1899. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  1900. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1901. [self presentViewController:_shareOC animated:YES completion:nil];
  1902. }
  1903. }
  1904. [self tableViewReloadData];
  1905. }
  1906. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1907. {
  1908. [_hud hideHud];
  1909. // Unauthorized
  1910. if (errorCode == kOCErrorServerUnauthorized)
  1911. [app openLoginView:self loginType:loginModifyPasswordUser];
  1912. if (errorCode != kOCErrorServerUnauthorized)
  1913. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1914. if (_shareOC)
  1915. [_shareOC reloadData];
  1916. [self tableViewReloadData];
  1917. }
  1918. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1919. {
  1920. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1921. metadataNet.action = actionShare;
  1922. metadataNet.fileID = metadata.fileID;
  1923. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  1924. metadataNet.password = password;
  1925. metadataNet.selector = selectorShare;
  1926. metadataNet.serverUrl = serverUrl;
  1927. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1928. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1929. }
  1930. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1931. {
  1932. [_hud hideHud];
  1933. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1934. // rimuoviamo la condivisione da db
  1935. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1936. if (result) {
  1937. appDelegate.sharesLink = result[0];
  1938. appDelegate.sharesUserAndGroup = result[1];
  1939. }
  1940. if (_shareOC)
  1941. [_shareOC reloadData];
  1942. [self tableViewReloadData];
  1943. }
  1944. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1945. {
  1946. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1947. metadataNet.action = actionUnShare;
  1948. metadataNet.fileID = metadata.fileID;
  1949. metadataNet.fileName = metadata.fileName;
  1950. metadataNet.selector = selectorUnshare;
  1951. metadataNet.serverUrl = serverUrl;
  1952. metadataNet.share = share;
  1953. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1954. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1955. }
  1956. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1957. {
  1958. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1959. metadataNet.action = actionUpdateShare;
  1960. metadataNet.fileID = metadata.fileID;
  1961. metadataNet.expirationTime = expirationTime;
  1962. metadataNet.password = password;
  1963. metadataNet.selector = selectorUpdateShare;
  1964. metadataNet.serverUrl = serverUrl;
  1965. metadataNet.share = share;
  1966. metadataNet.sharePermission = permission;
  1967. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1968. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1969. }
  1970. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1971. {
  1972. [_hud hideHud];
  1973. if (_shareOC)
  1974. [_shareOC reloadUserAndGroup:items];
  1975. }
  1976. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1977. {
  1978. [_hud hideHud];
  1979. // Unauthorized
  1980. if (errorCode == kOCErrorServerUnauthorized)
  1981. [app openLoginView:self loginType:loginModifyPasswordUser];
  1982. if (errorCode != kOCErrorServerUnauthorized)
  1983. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1984. }
  1985. - (void)getUserAndGroup:(NSString *)find
  1986. {
  1987. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1988. metadataNet.action = actionGetUserAndGroup;
  1989. metadataNet.options = find;
  1990. metadataNet.selector = selectorGetUserAndGroup;
  1991. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1992. [_hud visibleIndeterminateHud];
  1993. }
  1994. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1995. {
  1996. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1997. metadataNet.action = actionShareWith;
  1998. metadataNet.fileID = metadata.fileID;
  1999. metadataNet.directoryID = directoryID;
  2000. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2001. metadataNet.serverUrl = serverUrl;
  2002. metadataNet.selector = selectorShare;
  2003. metadataNet.share = user;
  2004. metadataNet.shareeType = shareeType;
  2005. metadataNet.sharePermission = permission;
  2006. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2007. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2008. }
  2009. - (void)openWindowShare:(tableMetadata *)metadata
  2010. {
  2011. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2012. if (!serverUrl) return;
  2013. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2014. metadataNet.action = actionReadShareServer;
  2015. metadataNet.fileID = metadata.fileID;
  2016. metadataNet.fileName = metadata.fileName;
  2017. metadataNet.selector = selectorOpenWindowShare;
  2018. metadataNet.serverUrl = serverUrl;
  2019. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2020. [_hud visibleIndeterminateHud];
  2021. }
  2022. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2023. {
  2024. CGPoint location = [tapGesture locationInView:self.tableView];
  2025. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2026. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2027. if (metadata)
  2028. [self openWindowShare:metadata];
  2029. }
  2030. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2031. {
  2032. CGPoint location = [tapGesture locationInView:self.tableView];
  2033. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2034. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2035. if (metadata) {
  2036. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2037. vc.metadata = metadata;
  2038. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2039. [self presentViewController:vc animated:YES completion:nil];
  2040. }
  2041. }
  2042. #pragma --------------------------------------------------------------------------------------------
  2043. #pragma mark ===== Favorite =====
  2044. #pragma --------------------------------------------------------------------------------------------
  2045. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2046. {
  2047. _dateReadDataSource = nil;
  2048. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2049. if (_isSearchMode)
  2050. [self readFolder:metadataNet.serverUrl];
  2051. else
  2052. [self reloadDatasource:metadataNet.serverUrl];
  2053. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2054. if (metadata.directory && metadata.favorite) {
  2055. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  2056. [app.activeFavorites addFavoriteFolder:dir];
  2057. }
  2058. }
  2059. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2060. {
  2061. // Unauthorized
  2062. if (errorCode == kOCErrorServerUnauthorized)
  2063. [app openLoginView:self loginType:loginModifyPasswordUser];
  2064. NSLog(@"[LOG] Setting Favorite failure error %lu, %@", (long)errorCode, message);
  2065. }
  2066. - (void)addFavorite:(tableMetadata *)metadata
  2067. {
  2068. if (metadata.directory) {
  2069. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2070. } else {
  2071. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2072. if (serverUrl)
  2073. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2074. }
  2075. }
  2076. - (void)removeFavorite:(tableMetadata *)metadata
  2077. {
  2078. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2079. }
  2080. #pragma --------------------------------------------------------------------------------------------
  2081. #pragma mark ===== Open in... =====
  2082. #pragma --------------------------------------------------------------------------------------------
  2083. - (void)openIn:(tableMetadata *)metadata
  2084. {
  2085. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2086. if (!serverUrl) return;
  2087. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2088. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2089. if ([self indexPathIsValid:indexPath])
  2090. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2091. }
  2092. #pragma --------------------------------------------------------------------------------------------
  2093. #pragma mark ===== Remove Local File =====
  2094. #pragma --------------------------------------------------------------------------------------------
  2095. - (void)removeLocalFile:(tableMetadata *)metadata
  2096. {
  2097. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2098. if (!serverUrl) return;
  2099. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2100. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2101. [self reloadDatasource:serverUrl];
  2102. }
  2103. #pragma --------------------------------------------------------------------------------------------
  2104. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2105. #pragma --------------------------------------------------------------------------------------------
  2106. - (void)orderTable:(NSString *)order
  2107. {
  2108. [CCUtility setOrderSettings:order];
  2109. // Clear data-read of DataSource
  2110. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2111. }
  2112. - (void)ascendingTable:(BOOL)ascending
  2113. {
  2114. [CCUtility setAscendingSettings:ascending];
  2115. // Clear data-read of DataSource
  2116. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2117. }
  2118. - (void)directoryOnTop:(BOOL)directoryOnTop
  2119. {
  2120. [CCUtility setDirectoryOnTop:directoryOnTop];
  2121. // Clear data-read of DataSource
  2122. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2123. }
  2124. - (void)tableGroupBy:(NSString *)groupBy
  2125. {
  2126. [CCUtility setGroupBySettings:groupBy];
  2127. // Clear data-read of DataSource
  2128. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2129. }
  2130. #pragma --------------------------------------------------------------------------------------------
  2131. #pragma mark ==== Menu LOGO ====
  2132. #pragma --------------------------------------------------------------------------------------------
  2133. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2134. {
  2135. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2136. return;
  2137. // Brand
  2138. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2139. return;
  2140. NSUInteger numInSession = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", app.activeAccount] sorted:nil ascending:NO] count];
  2141. NSUInteger numInQueue = [app.netQueue operationCount];
  2142. if (numInSession+numInQueue > 0) {
  2143. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2144. return;
  2145. }
  2146. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2147. NSMutableArray *menuArray = [NSMutableArray new];
  2148. for (NSString *account in listAccount) {
  2149. if ([account isEqualToString:app.activeAccount]) continue;
  2150. CCMenuItem *item = [[CCMenuItem alloc] init];
  2151. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2152. item.argument = account;
  2153. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2154. item.target = self;
  2155. item.action = @selector(changeDefaultAccount:);
  2156. [menuArray addObject:item];
  2157. }
  2158. if ([menuArray count] == 0)
  2159. return;
  2160. OptionalConfiguration options;
  2161. Color textColor, backgroundColor;
  2162. textColor.R = 0;
  2163. textColor.G = 0;
  2164. textColor.B = 0;
  2165. backgroundColor.R = 1;
  2166. backgroundColor.G = 1;
  2167. backgroundColor.B = 1;
  2168. options.arrowSize = 9;
  2169. options.marginXSpacing = 7;
  2170. options.marginYSpacing = 10;
  2171. options.intervalSpacing = 20;
  2172. options.menuCornerRadius = 6.5;
  2173. options.maskToBackground = NO;
  2174. options.shadowOfMenu = YES;
  2175. options.hasSeperatorLine = YES;
  2176. options.seperatorLineHasInsets = YES;
  2177. options.textColor = textColor;
  2178. options.menuBackgroundColor = backgroundColor;
  2179. CGRect rect = self.view.frame;
  2180. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2181. CGFloat safeAreaTop = 0;
  2182. CGFloat offsetY = 35;
  2183. if (@available(iOS 11, *)) {
  2184. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2185. }
  2186. rect.origin.y = locationY + safeAreaTop + offsetY;
  2187. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2188. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2189. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2190. }
  2191. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2192. {
  2193. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2194. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2195. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2196. if (tableAccount)
  2197. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2198. // go to home sweet home
  2199. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2200. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2201. });
  2202. }
  2203. #pragma --------------------------------------------------------------------------------------------
  2204. #pragma mark ==== ReMenu ====
  2205. #pragma --------------------------------------------------------------------------------------------
  2206. - (void)createReMenuBackgroundView:(REMenu *)menu
  2207. {
  2208. CGFloat safeAreaBottom = 0;
  2209. CGFloat safeAreaTop = 0;
  2210. CGFloat statusBar = 0;
  2211. if (@available(iOS 11, *)) {
  2212. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2213. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2214. }
  2215. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2216. statusBar = 20;
  2217. }
  2218. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2219. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2220. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2221. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2222. [UIView animateWithDuration:0.2 animations:^{
  2223. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2224. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2225. if (y>minimum) {
  2226. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2227. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2228. }
  2229. }];
  2230. }
  2231. - (void)createReMainMenu
  2232. {
  2233. NSString *ordinamento;
  2234. NSString *groupBy = _directoryGroupBy;
  2235. __block NSString *nuovoOrdinamento;
  2236. NSString *titoloNuovo, *titoloAttuale;
  2237. BOOL ascendente;
  2238. __block BOOL nuovoAscendente;
  2239. UIImage *image;
  2240. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2241. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2242. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2243. [self tableViewSelect:YES];
  2244. }
  2245. }];
  2246. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2247. ordinamento = _directoryOrder;
  2248. if ([ordinamento isEqualToString:@"fileName"]) {
  2249. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2250. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2251. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2252. nuovoOrdinamento = @"date";
  2253. }
  2254. if ([ordinamento isEqualToString:@"date"]) {
  2255. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2256. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2257. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2258. nuovoOrdinamento = @"fileName";
  2259. }
  2260. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2261. [self orderTable:nuovoOrdinamento];
  2262. }];
  2263. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2264. ascendente = [CCUtility getAscendingSettings];
  2265. if (ascendente) {
  2266. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2267. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2268. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2269. nuovoAscendente = false;
  2270. }
  2271. if (!ascendente) {
  2272. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2273. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2274. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2275. nuovoAscendente = true;
  2276. }
  2277. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2278. [self ascendingTable:nuovoAscendente];
  2279. }];
  2280. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2281. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2282. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2283. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2284. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2285. else [self tableGroupBy:@"alphabetic"];
  2286. }];
  2287. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2288. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2289. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2290. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2291. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2292. else [self tableGroupBy:@"typefile"];
  2293. }];
  2294. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2295. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2296. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2297. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2298. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2299. else [self tableGroupBy:@"date"];
  2300. }];
  2301. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2302. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2303. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2304. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2305. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2306. else [self directoryOnTop:YES];
  2307. }];
  2308. // REMENU --------------------------------------------------------------------------------------------------------------
  2309. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2310. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2311. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2312. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2313. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2314. app.reMainMenu.separatorHeight = 0.5;
  2315. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2316. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2317. app.reMainMenu.textColor = [UIColor blackColor];
  2318. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2319. app.reMainMenu.textShadowColor = nil;
  2320. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2321. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2322. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2323. app.reMainMenu.highlightedSeparatorColor = nil;
  2324. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2325. app.reMainMenu.highlightedTextShadowColor = nil;
  2326. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2327. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2328. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2329. app.reMainMenu.subtitleTextShadowColor = nil;
  2330. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2331. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2332. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2333. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2334. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2335. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2336. app.reMainMenu.borderWidth = 0.3;
  2337. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2338. app.reMainMenu.animationDuration = 0.2;
  2339. app.reMainMenu.closeAnimationDuration = 0.2;
  2340. app.reMainMenu.bounce = NO;
  2341. [app.reMainMenu setClosePreparationBlock:^{
  2342. // Backgroun reMenu (Gesture)
  2343. [_reMenuBackgroundView removeFromSuperview];
  2344. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2345. }];
  2346. }
  2347. - (void)toggleReMainMenu
  2348. {
  2349. if (app.reMainMenu.isOpen) {
  2350. [app.reMainMenu close];
  2351. } else {
  2352. [self createReMainMenu];
  2353. [app.reMainMenu showFromNavigationController:self.navigationController];
  2354. // Backgroun reMenu & (Gesture)
  2355. [self createReMenuBackgroundView:app.reMainMenu];
  2356. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2357. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2358. }
  2359. }
  2360. - (void)createReSelectMenu
  2361. {
  2362. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2363. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2364. [self deleteFile];
  2365. }];
  2366. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2367. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2368. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2369. }];
  2370. /*
  2371. if (app.isCryptoCloudMode) {
  2372. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2373. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2374. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2375. }];
  2376. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2377. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2378. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2379. }];
  2380. }
  2381. */
  2382. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2383. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2384. [self downloadSelectedFilesFolders];
  2385. }];
  2386. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2387. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2388. [self saveSelectedFiles];
  2389. }];
  2390. // REMENU --------------------------------------------------------------------------------------------------------------
  2391. /*
  2392. if (app.isCryptoCloudMode) {
  2393. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2394. } else {
  2395. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2396. }
  2397. */
  2398. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2399. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2400. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2401. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2402. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2403. app.reSelectMenu.separatorHeight = 0.5;
  2404. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2405. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2406. app.reSelectMenu.textColor = [UIColor blackColor];
  2407. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2408. app.reSelectMenu.textShadowColor = nil;
  2409. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2410. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2411. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2412. app.reSelectMenu.highlightedSeparatorColor = nil;
  2413. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2414. app.reSelectMenu.highlightedTextShadowColor = nil;
  2415. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2416. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2417. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2418. app.reSelectMenu.subtitleTextShadowColor = nil;
  2419. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2420. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2421. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2422. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2423. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2424. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2425. app.reSelectMenu.borderWidth = 0.3;
  2426. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2427. app.reSelectMenu.closeAnimationDuration = 0.2;
  2428. app.reSelectMenu.animationDuration = 0.2;
  2429. app.reSelectMenu.bounce = NO;
  2430. [app.reSelectMenu setClosePreparationBlock:^{
  2431. // Backgroun reMenu (Gesture)
  2432. [_reMenuBackgroundView removeFromSuperview];
  2433. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2434. }];
  2435. }
  2436. - (void)toggleReSelectMenu
  2437. {
  2438. if (app.reSelectMenu.isOpen) {
  2439. [app.reSelectMenu close];
  2440. } else {
  2441. [self createReSelectMenu];
  2442. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2443. // Backgroun reMenu & (Gesture)
  2444. [self createReMenuBackgroundView:app.reSelectMenu];
  2445. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2446. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2447. }
  2448. }
  2449. #pragma --------------------------------------------------------------------------------------------
  2450. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2451. #pragma --------------------------------------------------------------------------------------------
  2452. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2453. {
  2454. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2455. UITableView *tableView = (UITableView*)self.view;
  2456. CGPoint touchPoint = [recognizer locationInView:self.view];
  2457. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2458. if ([self indexPathIsValid:indexPath])
  2459. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2460. else
  2461. _metadata = nil;
  2462. [self becomeFirstResponder];
  2463. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2464. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2465. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2466. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2467. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2468. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2469. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2470. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2471. [menuController setMenuVisible:YES animated:YES];
  2472. }
  2473. }
  2474. - (BOOL)canBecomeFirstResponder
  2475. {
  2476. return YES;
  2477. }
  2478. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2479. {
  2480. // For copy file, copy files, Open in ... :
  2481. //
  2482. // NO Directory
  2483. // NO Error Passcode
  2484. // NO In Session mode (download/upload)
  2485. // NO Template
  2486. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2487. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2488. else return NO;
  2489. }
  2490. if (@selector(copyFiles:) == action) {
  2491. if (_isSelectedMode) {
  2492. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2493. for (tableMetadata *metadata in selectedMetadatas) {
  2494. if (!metadata.directory && metadata.session.length == 0)
  2495. return YES;
  2496. }
  2497. }
  2498. return NO;
  2499. }
  2500. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2501. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2502. NSArray *items = [pasteboard items];
  2503. if ([items count] == 1) {
  2504. // Value : (NSData) fileID
  2505. NSDictionary *dic = [items objectAtIndex:0];
  2506. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2507. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2508. if (fileID) {
  2509. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2510. if (metadata) {
  2511. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2512. if (account) {
  2513. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2514. if (directoryUser)
  2515. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2516. return YES;
  2517. }
  2518. }
  2519. }
  2520. }
  2521. return NO;
  2522. }
  2523. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2524. BOOL isValid = NO;
  2525. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2526. NSArray *items = [pasteboard items];
  2527. if ([items count] <= 1) return NO;
  2528. for (NSDictionary *dic in items) {
  2529. // Value : (NSData) fileID
  2530. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2531. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2532. if (fileID) {
  2533. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2534. if (metadata) {
  2535. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2536. if (account) {
  2537. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2538. if (directoryUser) {
  2539. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2540. isValid = YES;
  2541. } else {
  2542. isValid = NO;
  2543. break;
  2544. }
  2545. } else {
  2546. isValid = NO;
  2547. break;
  2548. }
  2549. } else {
  2550. isValid = NO;
  2551. break;
  2552. }
  2553. } else {
  2554. isValid = NO;
  2555. break;
  2556. }
  2557. } else {
  2558. isValid = NO;
  2559. break;
  2560. }
  2561. }
  2562. return isValid;
  2563. }
  2564. return NO;
  2565. }
  2566. /************************************ COPY ************************************/
  2567. - (void)copyFile:(id)sender
  2568. {
  2569. // Remove all item
  2570. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2571. pasteboard.items = [[NSArray alloc] init];
  2572. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2573. [self copyFileToPasteboard:_metadata];
  2574. } else {
  2575. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2576. if (serverUrl)
  2577. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2578. }
  2579. }
  2580. - (void)copyFiles:(id)sender
  2581. {
  2582. // Remove all item
  2583. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2584. pasteboard.items = [[NSArray alloc] init];
  2585. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2586. for (tableMetadata *metadata in selectedMetadatas) {
  2587. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2588. [self copyFileToPasteboard:metadata];
  2589. } else {
  2590. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2591. if (serverUrl)
  2592. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2593. }
  2594. }
  2595. [self tableViewSelect:NO];
  2596. }
  2597. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2598. {
  2599. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2600. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2601. // Value : (NSData) fileID
  2602. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2603. [items addObject:item];
  2604. [pasteboard setItems:items];
  2605. }
  2606. /************************************ OPEN IN ... ******************************/
  2607. - (void)openinFile:(id)sender
  2608. {
  2609. [self openIn:_metadata];
  2610. }
  2611. /************************************ PASTE ************************************/
  2612. - (void)pasteFile:(id)sender
  2613. {
  2614. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2615. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2616. }
  2617. - (void)pasteFileEncrypted:(id)sender
  2618. {
  2619. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2620. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2621. }
  2622. - (void)pasteFiles:(id)sender
  2623. {
  2624. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2625. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2626. }
  2627. - (void)pasteFilesEncrypted:(id)sender
  2628. {
  2629. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2630. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2631. }
  2632. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2633. {
  2634. float timer = 0;
  2635. for (NSDictionary *dic in items) {
  2636. // Value : (NSData) fileID
  2637. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2638. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2639. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2640. if (metadata) {
  2641. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2642. if (account) {
  2643. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2644. if (directoryUser) {
  2645. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2646. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]];
  2647. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2648. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:_serverUrl session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2649. });
  2650. timer += 0.1;
  2651. }
  2652. }
  2653. }
  2654. }
  2655. }
  2656. }
  2657. #pragma --------------------------------------------------------------------------------------------
  2658. #pragma mark ===== Lock Passcode =====
  2659. #pragma --------------------------------------------------------------------------------------------
  2660. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2661. {
  2662. return _failedAttempts;
  2663. }
  2664. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2665. {
  2666. return _lockUntilDate;
  2667. }
  2668. - (void)passcodeViewCloseButtonPressed:(id)sender
  2669. {
  2670. [self dismissViewControllerAnimated:YES completion:nil];
  2671. }
  2672. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2673. {
  2674. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2675. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2676. _lockUntilDate = nil;
  2677. _failedAttempts = 0;
  2678. aResultHandler(YES);
  2679. } else aResultHandler(NO);
  2680. } else aResultHandler(YES);
  2681. }
  2682. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2683. {
  2684. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2685. switch (aViewController.type) {
  2686. case BKPasscodeViewControllerCheckPasscodeType: {
  2687. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2688. // possiamo procedere alla prossima directory
  2689. [self performSegueDirectoryWithControlPasscode:false];
  2690. // avviamo la sessione Passcode Lock con now
  2691. app.sessionePasscodeLock = [NSDate date];
  2692. }
  2693. // disattivazione lock cartella
  2694. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2695. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2696. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2697. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2698. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2699. }
  2700. [self tableViewReloadData];
  2701. }
  2702. }
  2703. break;
  2704. default:
  2705. break;
  2706. }
  2707. }
  2708. - (void)comandoLockPassword
  2709. {
  2710. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2711. if (!serverUrl) return;
  2712. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2713. // se non è abilitato il Lock Passcode esci
  2714. if ([[CCUtility getBlockCode] length] == 0) {
  2715. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2716. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2717. [alertController addAction:okAction];
  2718. [self presentViewController:alertController animated:YES completion:nil];
  2719. return;
  2720. }
  2721. // se è richiesta la disattivazione si chiede la password
  2722. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2723. if (directory.lock) {
  2724. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2725. viewController.delegate = self;
  2726. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2727. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2728. viewController.inputViewTitlePassword = YES;
  2729. if ([CCUtility getSimplyBlockCode]) {
  2730. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2731. viewController.passcodeInputView.maximumLength = 6;
  2732. } else {
  2733. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2734. viewController.passcodeInputView.maximumLength = 64;
  2735. }
  2736. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2737. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2738. viewController.touchIDManager = touchIDManager;
  2739. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2740. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2741. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2742. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2743. [self presentViewController:navigationController animated:YES completion:nil];
  2744. return;
  2745. }
  2746. // ---------------- ACTIVATE PASSWORD
  2747. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2748. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2749. if ([self indexPathIsValid:indexPath])
  2750. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2751. } else {
  2752. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2753. }
  2754. }
  2755. #pragma mark -
  2756. #pragma --------------------------------------------------------------------------------------------
  2757. #pragma mark ===== Swipe Tablet -> menu =====
  2758. #pragma --------------------------------------------------------------------------------------------
  2759. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2760. {
  2761. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2762. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2763. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2764. return NO;
  2765. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2766. return NO;
  2767. else
  2768. return YES;
  2769. }
  2770. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2771. {
  2772. }
  2773. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2774. {
  2775. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2776. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2777. if (direction == MGSwipeDirectionRightToLeft) {
  2778. // Delete
  2779. if (index == 0)
  2780. [self swipeDelete:indexPath];
  2781. // More
  2782. if (index == 1)
  2783. [self swipeMore:indexPath];
  2784. }
  2785. if (direction == MGSwipeDirectionLeftToRight) {
  2786. if (_metadata.favorite)
  2787. [self removeFavorite:_metadata];
  2788. else
  2789. [self addFavorite:_metadata];
  2790. }
  2791. return YES;
  2792. }
  2793. - (void)swipeDelete:(NSIndexPath *)indexPath
  2794. {
  2795. // Directory locked ?
  2796. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2797. if (!lockServerUrl) return;
  2798. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2799. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) {
  2800. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2801. return;
  2802. }
  2803. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2804. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2805. [self performSelector:@selector(deleteFile) withObject:nil];
  2806. }]];
  2807. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2808. [alertController dismissViewControllerAnimated:YES completion:nil];
  2809. }]];
  2810. alertController.popoverPresentationController.sourceView = self.view;
  2811. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2812. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2813. [alertController.view layoutIfNeeded];
  2814. [self presentViewController:alertController animated:YES completion:nil];
  2815. }
  2816. - (void)swipeMore:(NSIndexPath *)indexPath
  2817. {
  2818. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2819. if (!serverUrl) return;
  2820. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  2821. titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2822. if (_metadata.favorite) {
  2823. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2824. } else {
  2825. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2826. }
  2827. if (_metadata.directory) {
  2828. // calcolo lockServerUrl
  2829. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2830. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2831. if (directory.lock)
  2832. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2833. else
  2834. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2835. }
  2836. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2837. // ******************************************* AHKActionSheet *******************************************
  2838. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2839. actionSheet.animationDuration = 0.2;
  2840. actionSheet.buttonHeight = 50.0;
  2841. actionSheet.cancelButtonHeight = 50.0f;
  2842. actionSheet.separatorHeight = 5.0f;
  2843. actionSheet.automaticallyTintButtonImages = @(NO);
  2844. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  2845. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2846. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2847. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2848. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2849. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2850. // ******************************************* DIRECTORY *******************************************
  2851. if (_metadata.directory) {
  2852. BOOL lockDirectory = NO;
  2853. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2854. // Directory bloccata ?
  2855. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, dirServerUrl]];
  2856. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  2857. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2858. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  2859. [actionSheet addButtonWithTitle: _metadata.fileName
  2860. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  2861. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2862. height: 50.0
  2863. type: AHKActionSheetButtonTypeDisabled
  2864. handler: nil
  2865. ];
  2866. if (!lockDirectory) {
  2867. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2868. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  2869. backgroundColor:[UIColor whiteColor]
  2870. height: 50.0
  2871. type:AHKActionSheetButtonTypeDefault
  2872. handler:^(AHKActionSheet *as) {
  2873. [self openWindowShare:_metadata];
  2874. }];
  2875. }
  2876. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  2877. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2878. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  2879. backgroundColor:[UIColor whiteColor]
  2880. height: 50.0
  2881. type:AHKActionSheetButtonTypeDefault
  2882. handler:^(AHKActionSheet *as) {
  2883. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2884. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2885. textField.text = _metadata.fileName;
  2886. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2887. //textField.delegate = self;
  2888. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2889. }];
  2890. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2891. NSLog(@"Cancel action");
  2892. }];
  2893. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2894. UITextField *fileName = alertController.textFields.firstObject;
  2895. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2896. }];
  2897. okAction.enabled = NO;
  2898. [alertController addAction:cancelAction];
  2899. [alertController addAction:okAction];
  2900. [self presentViewController:alertController animated:YES completion:nil];
  2901. }];
  2902. }
  2903. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  2904. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2905. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  2906. backgroundColor:[UIColor whiteColor]
  2907. height: 50.0
  2908. type:AHKActionSheetButtonTypeDefault
  2909. handler:^(AHKActionSheet *as) {
  2910. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2911. }];
  2912. }
  2913. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  2914. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2915. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  2916. backgroundColor:[UIColor whiteColor]
  2917. height: 50.0
  2918. type:AHKActionSheetButtonTypeDefault
  2919. handler:^(AHKActionSheet *as) {
  2920. // Settings new folder Automatatic upload
  2921. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  2922. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2923. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  2924. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  2925. if (app.activeAccount.length > 0 && app.activePhotos)
  2926. [app.activePhotos reloadDatasourceForced];
  2927. [self readFolder:serverUrl];
  2928. NSLog(@"[LOG] Update Folder Photo");
  2929. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  2930. if ([autoUploadPath length] > 0) {
  2931. [[CCSynchronize sharedSynchronize] readFileForFolder:_metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  2932. }
  2933. }];
  2934. }
  2935. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  2936. [actionSheet addButtonWithTitle:titoloLock
  2937. image:[UIImage imageNamed:@"actionSheetLock"]
  2938. backgroundColor:[UIColor whiteColor]
  2939. height: 50.0
  2940. type:AHKActionSheetButtonTypeEncrypted
  2941. handler:^(AHKActionSheet *as) {
  2942. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2943. }];
  2944. }
  2945. /*
  2946. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  2947. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  2948. image:[UIImage imageNamed:@"actionSheetCrypto"]
  2949. backgroundColor:[UIColor whiteColor]
  2950. height: 50.0
  2951. type:AHKActionSheetButtonTypeEncrypted
  2952. handler:^(AHKActionSheet *as) {
  2953. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  2954. }];
  2955. }
  2956. */
  2957. [actionSheet show];
  2958. }
  2959. // ******************************************* FILE *******************************************
  2960. if (!_metadata.directory) {
  2961. UIImage *iconHeader;
  2962. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2963. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  2964. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  2965. else
  2966. iconHeader = [UIImage imageNamed:_metadata.iconName];
  2967. [actionSheet addButtonWithTitle: _metadata.fileName
  2968. image: iconHeader
  2969. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2970. height: 50.0
  2971. type: AHKActionSheetButtonTypeDisabled
  2972. handler: nil
  2973. ];
  2974. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2975. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"]color:[NCBrandColor sharedInstance].brand]
  2976. backgroundColor:[UIColor whiteColor]
  2977. height: 50.0
  2978. type:AHKActionSheetButtonTypeDefault
  2979. handler:^(AHKActionSheet *as) {
  2980. [self openWindowShare:_metadata];
  2981. }];
  2982. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2983. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  2984. backgroundColor:[UIColor whiteColor]
  2985. height: 50.0
  2986. type:AHKActionSheetButtonTypeDefault
  2987. handler:^(AHKActionSheet *as) {
  2988. [self performSelector:@selector(openIn:) withObject:_metadata];
  2989. }];
  2990. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2991. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  2992. backgroundColor:[UIColor whiteColor]
  2993. height: 50.0
  2994. type:AHKActionSheetButtonTypeDefault
  2995. handler:^(AHKActionSheet *as) {
  2996. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2997. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2998. textField.text = _metadata.fileName;
  2999. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3000. }];
  3001. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3002. NSLog(@"Cancel action");
  3003. }];
  3004. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3005. UITextField *fileName = alertController.textFields.firstObject;
  3006. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3007. }];
  3008. okAction.enabled = NO;
  3009. [alertController addAction:cancelAction];
  3010. [alertController addAction:okAction];
  3011. [self presentViewController:alertController animated:YES completion:nil];
  3012. }];
  3013. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3014. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3015. backgroundColor:[UIColor whiteColor]
  3016. height: 50.0
  3017. type:AHKActionSheetButtonTypeDefault
  3018. handler:^(AHKActionSheet *as) {
  3019. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3020. }];
  3021. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3022. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3023. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3024. backgroundColor:[UIColor whiteColor]
  3025. height: 50.0
  3026. type:AHKActionSheetButtonTypeDefault
  3027. handler:^(AHKActionSheet *as) {
  3028. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3029. }];
  3030. }
  3031. /*
  3032. if (app.isCryptoCloudMode) {
  3033. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3034. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3035. backgroundColor:[UIColor whiteColor]
  3036. height: 50.0
  3037. type:AHKActionSheetButtonTypeEncrypted
  3038. handler:^(AHKActionSheet *as) {
  3039. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3040. }];
  3041. }
  3042. */
  3043. #ifdef DEBUG
  3044. /*
  3045. [actionSheet addButtonWithTitle:@"Hide file"
  3046. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"admin"] color:[NCBrandColor sharedInstance].brand]
  3047. backgroundColor:[UIColor whiteColor]
  3048. height: 50.0
  3049. type:AHKActionSheetButtonTypeDefault
  3050. handler:^(AHKActionSheet *as) {
  3051. [[NCManageDatabase sharedInstance] setMetadataStatusWithFileID:_metadata.fileID status:k_metadataStatusHide];
  3052. [self reloadDatasource];
  3053. }];
  3054. */
  3055. #endif
  3056. [actionSheet show];
  3057. }
  3058. }
  3059. #pragma --------------------------------------------------------------------------------------------
  3060. #pragma mark - ==== Datasource ====
  3061. #pragma --------------------------------------------------------------------------------------------
  3062. - (void)clearDateReadDataSource:(NSNotification *)notification
  3063. {
  3064. _dateReadDataSource = Nil;
  3065. [self reloadDatasource];
  3066. }
  3067. - (void)reloadDatasource
  3068. {
  3069. [self reloadDatasource:_serverUrl];
  3070. }
  3071. - (void)reloadDatasource:(NSString *)serverUrl
  3072. {
  3073. // test
  3074. if (app.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3075. return;
  3076. // Search Mode
  3077. if(_isSearchMode) {
  3078. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3079. [self tableViewReloadData];
  3080. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3081. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3082. _noFilesSearchDescription = @"";
  3083. }
  3084. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3085. _noFilesSearchTitle = @"";
  3086. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3087. }
  3088. [self.tableView reloadEmptyDataSet];
  3089. return;
  3090. }
  3091. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3092. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3093. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3094. if (main) {
  3095. [main reloadDatasource];
  3096. } else {
  3097. [self tableViewReloadData];
  3098. [app.activeTransfers reloadDatasource];
  3099. }
  3100. return;
  3101. }
  3102. [app.activeTransfers reloadDatasource];
  3103. // Settaggio variabili per le ottimizzazioni
  3104. _directoryGroupBy = [CCUtility getGroupBySettings];
  3105. _directoryOrder = [CCUtility getOrderSettings];
  3106. // Controllo data lettura Data Source
  3107. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  3108. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3109. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3110. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3111. _dateReadDataSource = [NSDate date];
  3112. // Data Source
  3113. NSString *sorted = _directoryOrder;
  3114. if ([sorted isEqualToString:@"fileName"])
  3115. sorted = @"fileName";
  3116. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3117. if (directoryID) {
  3118. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", app.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3119. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3120. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3121. }
  3122. } else {
  3123. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3124. }
  3125. [self tableViewReloadData];
  3126. }
  3127. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3128. {
  3129. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3130. if (selectedRows.count > 0) {
  3131. for (NSIndexPath *selectionIndex in selectedRows) {
  3132. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3133. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3134. [metadatas addObject:metadata];
  3135. }
  3136. }
  3137. return metadatas;
  3138. }
  3139. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3140. {
  3141. NSInteger section = indexPath.section + 1;
  3142. NSInteger row = indexPath.row + 1;
  3143. NSInteger totSections = [_sectionDataSource.sections count] ;
  3144. if ((totSections < section) || (section > totSections)) {
  3145. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3146. return nil;
  3147. }
  3148. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3149. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3150. if (fileIDs) {
  3151. NSInteger totRows =[fileIDs count] ;
  3152. if ((totRows < row) || (row > totRows)) {
  3153. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3154. return nil;
  3155. }
  3156. } else {
  3157. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3158. return nil;
  3159. }
  3160. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3161. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3162. return metadata;
  3163. }
  3164. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3165. {
  3166. NSInteger totSections =[_sectionDataSource.sections count] ;
  3167. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3168. return nil;
  3169. }
  3170. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3171. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3172. }
  3173. #pragma --------------------------------------------------------------------------------------------
  3174. #pragma mark - ==== Table ====
  3175. #pragma --------------------------------------------------------------------------------------------
  3176. - (void)tableViewSelect:(BOOL)edit
  3177. {
  3178. // chiudiamo eventuali swipe aperti
  3179. if (edit)
  3180. [self.tableView setEditing:NO animated:NO];
  3181. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3182. [self.tableView setEditing:edit animated:YES];
  3183. _isSelectedMode = edit;
  3184. if (edit)
  3185. [self setUINavigationBarSelected];
  3186. else
  3187. [self setUINavigationBarDefault];
  3188. [_selectedFileIDsMetadatas removeAllObjects];
  3189. [self setTitle];
  3190. }
  3191. - (void)tableViewReloadData
  3192. {
  3193. // store selected cells before relod
  3194. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3195. //store swipeOffset before relod
  3196. [_statusSwipeCell removeAllObjects];
  3197. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3198. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3199. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3200. }
  3201. // reload table view
  3202. [self.tableView reloadData];
  3203. // selected cells stored
  3204. for (NSIndexPath *path in indexPaths)
  3205. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3206. [self setTableViewFooter];
  3207. if (self.tableView.editing)
  3208. [self setTitle];
  3209. }
  3210. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3211. {
  3212. if (tableView.editing == 1) {
  3213. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3214. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3215. return NO;
  3216. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3217. return NO;
  3218. else
  3219. return YES;
  3220. } else {
  3221. [_selectedFileIDsMetadatas removeAllObjects];
  3222. }
  3223. return YES;
  3224. }
  3225. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3226. {
  3227. return 60;
  3228. }
  3229. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3230. {
  3231. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3232. }
  3233. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3234. {
  3235. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3236. }
  3237. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3238. {
  3239. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3240. NSString *sectionTitle = [sections objectAtIndex:section];
  3241. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3242. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3243. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3244. return 20.f;
  3245. }
  3246. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3247. {
  3248. float shift;
  3249. UIVisualEffectView *visualEffectView;
  3250. NSString *titleSection;
  3251. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3252. return nil;
  3253. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3254. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3255. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3256. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3257. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3258. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3259. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3260. else titleSection = NSLocalizedString(titleSection,nil);
  3261. // Format title
  3262. NSString *currentDevice = [CCUtility currentDevice];
  3263. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3264. visualEffectView = [[UIVisualEffectView alloc] init];
  3265. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3266. } else {
  3267. UIVisualEffect *blurEffect;
  3268. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3269. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3270. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3271. }
  3272. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3273. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3274. shift = - 35;
  3275. else
  3276. shift = - 20;
  3277. } else shift = - 10;
  3278. // Title
  3279. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3280. titleLabel.backgroundColor = [UIColor clearColor];
  3281. titleLabel.textColor = [UIColor blackColor];
  3282. titleLabel.font = [UIFont systemFontOfSize:12];
  3283. titleLabel.textAlignment = NSTextAlignmentLeft;
  3284. titleLabel.text = titleSection;
  3285. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3286. [visualEffectView.contentView addSubview:titleLabel];
  3287. // Elements
  3288. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3289. elementLabel.backgroundColor = [UIColor clearColor];
  3290. elementLabel.textColor = [UIColor blackColor];;
  3291. elementLabel.font = [UIFont systemFontOfSize:12];
  3292. elementLabel.textAlignment = NSTextAlignmentRight;
  3293. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3294. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3295. NSUInteger rowsCount = [metadatas count];
  3296. if (rowsCount == 0) return nil;
  3297. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3298. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3299. [visualEffectView.contentView addSubview:elementLabel];
  3300. return visualEffectView;
  3301. }
  3302. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3303. {
  3304. return [_sectionDataSource.sections indexOfObject:title];
  3305. }
  3306. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3307. {
  3308. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3309. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3310. else
  3311. return nil;
  3312. }
  3313. /*
  3314. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3315. {
  3316. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3317. }
  3318. }
  3319. */
  3320. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3321. {
  3322. NSString *typeCell;
  3323. NSString *dataFile;
  3324. NSString *lunghezzaFile;
  3325. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3326. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3327. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3328. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3329. if (!serverUrl)
  3330. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3331. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3332. else typeCell = @"CellMainTransfer";
  3333. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3334. // variable base
  3335. cell.delegate = self;
  3336. cell.indexPath = indexPath;
  3337. // separator
  3338. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3339. // change color selection
  3340. UIView *selectionColor = [[UIView alloc] init];
  3341. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3342. cell.selectedBackgroundView = selectionColor;
  3343. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3344. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3345. // ----------------------------------------------------------------------------------------------------------
  3346. // DEFAULT
  3347. // ----------------------------------------------------------------------------------------------------------
  3348. cell.file.image = nil;
  3349. cell.status.image = nil;
  3350. cell.favorite.image = nil;
  3351. cell.shared.image = nil;
  3352. cell.local.image = nil;
  3353. cell.labelTitle.enabled = YES;
  3354. cell.labelTitle.text = @"";
  3355. cell.labelInfoFile.enabled = YES;
  3356. cell.labelInfoFile.text = @"";
  3357. cell.progressView.progress = 0.0;
  3358. cell.progressView.hidden = YES;
  3359. cell.cancelTaskButton.hidden = YES;
  3360. cell.reloadTaskButton.hidden = YES;
  3361. cell.stopTaskButton.hidden = YES;
  3362. cell.labelTitle.textColor = [UIColor blackColor];
  3363. // ----------------------------------------------------------------------------------------------------------
  3364. // File Name & Folder
  3365. // ----------------------------------------------------------------------------------------------------------
  3366. // nome del file
  3367. cell.labelTitle.text = metadata.fileName;
  3368. // è una directory
  3369. if (metadata.directory) {
  3370. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3371. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3372. lunghezzaFile = @" ";
  3373. // ----------------------------------------------------------------------------------------------------------
  3374. // Favorite Folder
  3375. // ----------------------------------------------------------------------------------------------------------
  3376. if (metadata.favorite) {
  3377. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3378. }
  3379. } else {
  3380. // File
  3381. dataFile = [CCUtility dateDiff:metadata.date];
  3382. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3383. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3384. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3385. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3386. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3387. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3388. cell.local.image = [UIImage imageNamed:@"local"];
  3389. else
  3390. cell.local.image = nil;
  3391. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3392. cell.accessoryType = UITableViewCellAccessoryNone;
  3393. }
  3394. // ----------------------------------------------------------------------------------------------------------
  3395. // File Image View
  3396. // ----------------------------------------------------------------------------------------------------------
  3397. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3398. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3399. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3400. } else {
  3401. if (metadata.directory)
  3402. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3403. else
  3404. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3405. if (metadata.thumbnailExists)
  3406. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3407. }
  3408. // ----------------------------------------------------------------------------------------------------------
  3409. // Image Status cyptated & Lock Passcode
  3410. // ----------------------------------------------------------------------------------------------------------
  3411. // Directory con passcode lock attivato
  3412. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3413. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3414. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3415. cell.status.image = [UIImage imageNamed:@"passcode"];
  3416. // ----------------------------------------------------------------------------------------------------------
  3417. // Favorite
  3418. // ----------------------------------------------------------------------------------------------------------
  3419. if (metadata.favorite) {
  3420. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3421. }
  3422. // ----------------------------------------------------------------------------------------------------------
  3423. // Share
  3424. // ----------------------------------------------------------------------------------------------------------
  3425. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3426. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3427. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3428. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3429. // Aggiungiamo il Tap per le shared
  3430. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3431. // Shared with you
  3432. if (isShare) {
  3433. if (metadata.directory) {
  3434. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3435. cell.accessoryType = UITableViewCellAccessoryNone;
  3436. }
  3437. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3438. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3439. [tap setNumberOfTapsRequired:1];
  3440. cell.shared.userInteractionEnabled = YES;
  3441. [cell.shared addGestureRecognizer:tap];
  3442. }
  3443. // Mounted with you
  3444. if (isMounted) {
  3445. if (metadata.directory) {
  3446. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3447. cell.accessoryType = UITableViewCellAccessoryNone;
  3448. }
  3449. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3450. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3451. [tap setNumberOfTapsRequired:1];
  3452. cell.shared.userInteractionEnabled = YES;
  3453. [cell.shared addGestureRecognizer:tap];
  3454. }
  3455. // You share
  3456. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3457. if (metadata.directory) {
  3458. if ([shareLink length] > 0)
  3459. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3460. if ([shareUserAndGroup length] > 0)
  3461. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3462. cell.shared.userInteractionEnabled = NO;
  3463. } else {
  3464. if ([shareLink length] > 0)
  3465. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3466. if ([shareUserAndGroup length] > 0)
  3467. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3468. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3469. [tap setNumberOfTapsRequired:1];
  3470. cell.shared.userInteractionEnabled = YES;
  3471. [cell.shared addGestureRecognizer:tap];
  3472. }
  3473. }
  3474. } else {
  3475. cell.shared.userInteractionEnabled = NO;
  3476. }
  3477. // ----------------------------------------------------------------------------------------------------------
  3478. // downloadFile
  3479. // ----------------------------------------------------------------------------------------------------------
  3480. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3481. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3482. // sessionTaskIdentifier : RELOAD + STOP
  3483. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3484. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3485. cell.cancelTaskButton.hidden = NO;
  3486. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3487. cell.reloadTaskButton.hidden = NO;
  3488. }
  3489. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3490. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3491. if (progress > 0) {
  3492. cell.progressView.progressTintColor = [UIColor blackColor];
  3493. cell.progressView.progress = progress;
  3494. cell.progressView.hidden = NO;
  3495. }
  3496. // ----------------------------------------------------------------------------------------------------------
  3497. // downloadFile Error
  3498. // ----------------------------------------------------------------------------------------------------------
  3499. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3500. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3501. if ([metadata.sessionError length] == 0)
  3502. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3503. else
  3504. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3505. }
  3506. }
  3507. // ----------------------------------------------------------------------------------------------------------
  3508. // uploadFile
  3509. // ----------------------------------------------------------------------------------------------------------
  3510. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3511. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3512. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3513. cell.cancelTaskButton.hidden = NO;
  3514. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3515. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3516. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3517. cell.reloadTaskButton.hidden = NO;
  3518. cell.stopTaskButton.hidden = YES;
  3519. } else {
  3520. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3521. cell.stopTaskButton.hidden = NO;
  3522. cell.reloadTaskButton.hidden = YES;
  3523. }
  3524. // se non c'è una preview in bianconero metti l'immagine di default
  3525. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3526. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3527. cell.labelTitle.enabled = NO;
  3528. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3529. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3530. if (progress > 0) {
  3531. cell.progressView.progressTintColor = [UIColor blackColor];
  3532. cell.progressView.progress = progress;
  3533. cell.progressView.hidden = NO;
  3534. }
  3535. // ----------------------------------------------------------------------------------------------------------
  3536. // uploadFileError
  3537. // ----------------------------------------------------------------------------------------------------------
  3538. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3539. cell.labelTitle.enabled = NO;
  3540. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3541. if ([metadata.sessionError length] == 0)
  3542. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3543. else
  3544. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3545. }
  3546. }
  3547. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3548. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3549. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3550. // ======== MGSwipe ========
  3551. if (metadata.favorite)
  3552. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_unfavorite_", nil)] icon:[UIImage imageNamed:@"swipeUnfavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3553. else
  3554. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_favorite_", nil)] icon:[UIImage imageNamed:@"swipeFavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3555. cell.leftExpansion.buttonIndex = 0;
  3556. cell.leftExpansion.fillOnTrigger = NO;
  3557. //centerIconOverText
  3558. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3559. [favoriteButton centerIconOverText];
  3560. //Right
  3561. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_delete_", nil)] icon:[UIImage imageNamed:@"swipeDelete"] backgroundColor:[UIColor redColor]], [MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_more_", nil)] icon:[UIImage imageNamed:@"swipeMore"] backgroundColor:[UIColor lightGrayColor]]];
  3562. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3563. //centerIconOverText
  3564. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3565. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3566. [deleteButton centerIconOverText];
  3567. [moreButton centerIconOverText];
  3568. //restore swipeOffset after relod
  3569. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3570. if (swipeOffset < 0) {
  3571. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3572. [_statusSwipeCell removeObjectForKey:indexPath];
  3573. } else if (swipeOffset > 0) {
  3574. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3575. [_statusSwipeCell removeObjectForKey:indexPath];
  3576. }
  3577. return cell;
  3578. }
  3579. - (void)setTableViewFooter
  3580. {
  3581. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3582. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3583. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3584. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3585. UIFont *appFont = [UIFont systemFontOfSize:12];
  3586. footerLabel.font = appFont;
  3587. footerLabel.textColor = [UIColor grayColor];
  3588. footerLabel.backgroundColor = [UIColor clearColor];
  3589. footerLabel.textAlignment = NSTextAlignmentCenter;
  3590. NSString *folders;
  3591. NSString *files;
  3592. NSString *footerText;
  3593. if (_sectionDataSource.directories > 1) {
  3594. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3595. } else if (_sectionDataSource.directories == 1){
  3596. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3597. } else {
  3598. folders = @"";
  3599. }
  3600. if (_sectionDataSource.files > 1) {
  3601. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3602. } else if (_sectionDataSource.files == 1){
  3603. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3604. } else {
  3605. files = @"";
  3606. }
  3607. if ([folders isEqualToString:@""]) {
  3608. footerText = files;
  3609. } else if ([files isEqualToString:@""]) {
  3610. footerText = folders;
  3611. } else {
  3612. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3613. }
  3614. footerLabel.text = footerText;
  3615. [footerView addSubview:footerLabel];
  3616. [self.tableView setTableFooterView:footerView];
  3617. }
  3618. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3619. {
  3620. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3621. // settiamo il record file.
  3622. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3623. if (!_metadata)
  3624. return;
  3625. // se non può essere selezionata deseleziona
  3626. if ([cell isEditing] == NO)
  3627. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3628. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3629. if (self.tableView.editing) {
  3630. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3631. [self setTitle];
  3632. return;
  3633. }
  3634. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3635. if (!serverUrl) return;
  3636. // se è in corso una sessione
  3637. if ([_metadata.session length] > 0) return;
  3638. // file
  3639. if (_metadata.directory == NO) {
  3640. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3641. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3642. #ifdef DEBUG
  3643. // TEST ENCRYPTED
  3644. if ([_metadata.fileName containsString:@".dms"]) {
  3645. [[NCClientEncryption sharedManager] decryptMetadata:_metadata activeUrl:app.directoryUser];
  3646. }
  3647. #endif
  3648. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3649. } else {
  3650. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3651. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3652. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3653. }
  3654. }
  3655. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3656. }
  3657. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3658. {
  3659. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3660. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3661. [self setTitle];
  3662. }
  3663. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3664. {
  3665. if (!indexPath)
  3666. return NO;
  3667. NSInteger section = indexPath.section;
  3668. NSInteger row = indexPath.row;
  3669. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3670. if (section > lastSectionIndex || lastSectionIndex < 0)
  3671. return NO;
  3672. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3673. if (rowCount < 0)
  3674. return NO;
  3675. return row <= rowCount;
  3676. }
  3677. #pragma --------------------------------------------------------------------------------------------
  3678. #pragma mark ===== Navigation ====
  3679. #pragma --------------------------------------------------------------------------------------------
  3680. - (BOOL)shouldPerformSegue
  3681. {
  3682. // if background return
  3683. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3684. if (self.view.window == NO)
  3685. return NO;
  3686. // Collapsed ma siamo già in detail esci
  3687. if (self.splitViewController.isCollapsed)
  3688. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3689. return YES;
  3690. }
  3691. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3692. {
  3693. id viewController = segue.destinationViewController;
  3694. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3695. tableMetadata *metadata;
  3696. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3697. UINavigationController *nav = viewController;
  3698. _detailViewController = (CCDetail *)nav.topViewController;
  3699. } else {
  3700. _detailViewController = segue.destinationViewController;
  3701. }
  3702. if ([sender isKindOfClass:[tableMetadata class]]) {
  3703. metadata = sender;
  3704. [allRecordsDataSourceImagesVideos addObject:sender];
  3705. } else {
  3706. metadata = _metadata;
  3707. for (NSString *fileID in _sectionDataSource.allEtag) {
  3708. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3709. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3710. [allRecordsDataSourceImagesVideos addObject:metadata];
  3711. }
  3712. }
  3713. _detailViewController.metadataDetail = metadata;
  3714. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3715. _detailViewController.dateFilterQuery = nil;
  3716. [_detailViewController setTitle:metadata.fileName];
  3717. }
  3718. // can i go to next viewcontroller
  3719. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3720. {
  3721. NSString *nomeDir;
  3722. if(self.tableView.editing == NO) {
  3723. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3724. if (!serverUrl) return;
  3725. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3726. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3727. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  3728. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  3729. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3730. viewController.delegate = self;
  3731. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3732. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3733. viewController.inputViewTitlePassword = YES;
  3734. if ([CCUtility getSimplyBlockCode]) {
  3735. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3736. viewController.passcodeInputView.maximumLength = 6;
  3737. } else {
  3738. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3739. viewController.passcodeInputView.maximumLength = 64;
  3740. }
  3741. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3742. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3743. viewController.touchIDManager = touchIDManager;
  3744. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3745. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3746. //viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3747. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3748. [self presentViewController:navController animated:YES completion:nil];
  3749. return;
  3750. }
  3751. nomeDir = _metadata.fileName;
  3752. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3753. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  3754. if (!viewController) {
  3755. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  3756. viewController.serverUrl = serverUrlPush;
  3757. viewController.titleMain = _metadata.fileName;
  3758. viewController.textBackButton = _titleMain;
  3759. // save self
  3760. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  3761. [self.navigationController pushViewController:viewController animated:YES];
  3762. } else {
  3763. if (viewController.isViewLoaded) {
  3764. // Fix : Application tried to present modally an active controller
  3765. if ([self.navigationController isBeingPresented]) {
  3766. // being presented
  3767. } else if ([self.navigationController isMovingToParentViewController]) {
  3768. // being pushed
  3769. } else {
  3770. [self.navigationController pushViewController:viewController animated:YES];
  3771. }
  3772. }
  3773. }
  3774. }
  3775. }
  3776. @end